Reputation: 1
Using eclipse btw.
Why does this:
public class charCounter {
public static void main(String[] args)
throws java.io.IOException {
char entry;
int count;
for (count = 0;;){
System.out.println("Press \" . \" to exit.");
entry = (char) System.in.read();
if (entry != '.')
count++;
else break;
}
System.out.println("Number of entries: " + count);
}
}
result in 3x the amount of "count" as it should be? That is when I enter a, b, and c, for example, and then press '.', it says "Number of entries: 12"
I'm reading through "Java, A Beginner's Guide"
and I don't understand what I did wrong? I'm new but not stupid so I don't see the logic behind this. Is it simply a bug or too fast of a mechanic behind the for
loop to be used for such short code?
Upvotes: 0
Views: 85
Reputation: 836
It's a bug in your code. When you push <enter>
you are actually inserting special (invisible) characters \r\n
(also known as carriage return and newline). This is why every time you push enter you get extra characters.
You effectively have the input (spaces added for clarity only):
a \r \n b \r \n c \r \n . \r \n
even though your console looks like:
a
b
c
.
System.in.read reads one character at a time, so your loop will actually execute thrice for the sequence a\r\n
, once for a
and once for \r
and once for \n
.
Upvotes: 2