1

I wrote a for loop like this:

for(int i = 0; (char) System.in.read() != 's'; i++){ System.out.print(i); } 

I expected the program to keep printing numbers until I type s on the keyboard. However, every time I typed a letter, I got three numbers on the command prompt:

a 012 q 345 

There should be only one number printed on the console after each letter typed, but there are three. Why?

7
  • 3
    i assume you type a letter followed by the Enter key? Did you account for reading the line feed and carriage return characters? Commented Dec 6, 2015 at 2:27
  • Your issue is not with the for-loop, it is with the behavior of System.in.read(), which is buffered and waits until end-of-line. Commented Dec 6, 2015 at 2:28
  • I actually get two numbers in the console. Commented Dec 6, 2015 at 2:29
  • @MichaelQueue Probably because Gropai has Windows, and you have a different OS. Commented Dec 6, 2015 at 2:30
  • @Brian Goetz Why does buffering cause more numbers to be printed? Commented Dec 6, 2015 at 2:32

2 Answers 2

3

As several of your commenters stated, the issue isn't with the for() loop, but with System.in.read(), which will also provide the Carriage Return / Line Feed from the input stream as characters (they are also why your output is spread across several lines, as opposed to everything being on one line)

Sign up to request clarification or add additional context in comments.

2 Comments

Then how can I fix the problem?
There are several forms of InputStream.read() (Please see docs.oracle.com/javase/7/docs/api/java/io/InputStream.html) that you can use, including one that passes a byte[] so you can retrieve all of the characters that were available at the time the for loop executed (of which you could check the content with a for ... in loop inside of your outer loop docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
2

Like Brian said in the comments, it's because the input is buffered. When you type a and then hit the enter key that enter key is flushing the buffer and you are seeing the loop execute 3 times. Once for the first character, a, and twice more for the \n and \r characters representing the new line and carriage return characters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.