tags:

views:

99

answers:

3
+1  Q: 

count char in java

what is wrong in this code?

import java.io.IOException;
import java.util.*;
public class char_digit {
    public static void main(String[] args) throws IOException {
        int count=0;

        while (true){
            char t=(char) System.in.read();
            if (t=='0'){
                break;
            }
            count++;

        }
        System.out.println(count);
    }
}


run:
a
b
c
d
e
f
0
12
+8  A: 

You're counting the newlines as well as the other characters. Try something like if (t == '\n') continue; before the current if.

Skilldrick
+2  A: 

nothing is wrong. The carriage return also counts as a char (or 2 depending on your OS)

Redlab
+1  A: 

The problem is that you're counting whitespace characters as well, which are inserted when you hit the Enter button into the console. One quick fix is to use Character.isWhitespace check as follows:

        if (t=='0'){
            break;
        } else if (!Character.isWhitespace(t)) {
            count++;
        }

Depending on what you want to do, though, a java.util.Scanner may serve your purpose better. Using System.in.read directly is highly atypical, and especially if you're reading char, where a Reader is more suitable.

Related questions

polygenelubricants