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
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.isWhitespacecheck as follows:Depending on what you want to do, though, a
java.util.Scannermay serve your purpose better. UsingSystem.in.readdirectly is highly atypical, and especially if you’re readingchar, where aReaderis more suitable.Related questions