for loop in Java runs 3 times before taking next input

前端 未结 2 465
再見小時候
再見小時候 2020-11-27 22:07

I am new to Java and learning it. I was trying out a code to actually see how the for-each loop works in Java. But I faced a problem regarding that. My code is simple :

2条回答
  •  Happy的楠姐
    2020-11-27 23:01

    From the Java API:

    Reads the next byte of data from the input stream.

    What happens is when you type a followed by a newline, there are actually three bytes to read (I'm guessing a followed by carriage return and newline). Hence, the input you provide is enough to keep read() running for three iterations.

    I recommend you to use Scanner for input reading instead.

提交回复
热议问题