Reputation:
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
Upvotes: 1
Views: 346
Reputation: 383726
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.
Upvotes: 1
Reputation: 3118
nothing is wrong. The carriage return also counts as a char (or 2 depending on your OS)
Upvotes: 2
Reputation: 70819
You're counting the newlines as well as the other characters. Try something like if (t == '\n') continue;
before the current if
.
Upvotes: 8