Why does this simple counter double in a simple Java application?

public class MyTestClass {
    public static void main(String[] args) throws Exception {
        char c;
        InputStreamReader reader = (new InputStreamReader(System.in));
        System.out.println("Enter chars:");
        OutputStream outputStream = new BufferedOutputStream(System.out);
        int counter = 0;
        do {
            counter++;
            c = (char) reader.read();
            outputStream.write(c);
            outputStream.flush();
            System.out.println(counter);
        } while (c != 'q');
    }
}

      

I'm trying to just type in a character and then hit enter.

What will I see:

Enter chars:
a
a1

2
b
b3

4

      

+3


source to share


3 answers


\n

is also a character, every time you hit enter you add a character. For example, use nextLine()

or filter out blanks when you see it (check the symbol, ignore it if it is a blank).



+4


source


When you hit Enter, your code will receive a newline character. This is why you see a blank line after a1

and b3

.



If you want to filter out new lines check c

on '\n'

.

+4


source


Your "Enter" character is also considered a valid input character. You can use a condition filter to return a quote or decrease the count value by 1 each time.

+2


source







All Articles