0

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?

Naman
  • 27,789
  • 26
  • 218
  • 353

1 Answers1

2

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.

Brandon McKenzie
  • 1,655
  • 11
  • 26
Shadowen
  • 838
  • 5
  • 14
  • Thank you! This makes sense. Now to figure out how to ignore the invisible keys... I guess I just have to include not \r or \n conditions from now on.. – Paradigm Wolf Dec 12 '16 at 22:18
  • 1
    So long as you iterate through single characters like that, that is what you have to do. That being said, you may wish to read into `Scanner` and `BufferedReader`, as you may be reinventing functionality they already do. – Brandon McKenzie Dec 13 '16 at 14:51