简体   繁体   English

关于Java中的for循环的困惑

[英]Confusion about for loop in Java

I wrote a for loop like this: 我写了这样的for循环:

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. 我希望程序在我在键盘上键入s之前一直打印数字。 However, every time I typed a letter, I got three numbers on the command prompt: 但是,每次键入字母时,命令提示符下都会出现three numbers

a
012
q
345

There should be only one number printed on the console after each letter typed, but there are three. 每个字母键入后,在控制台上应该只印有一个数字,但是有三个。 Why? 为什么?

正如您的一些评论者所述,问题不在于for()循环,而在于System.in.read(),该问题还将提供输入流中的回车符/换行符作为字符(这也是为什么您的输出分布在多行中,而不是所有内容都在一行中)

Like Brian said in the comments, it's because the input is buffered. 就像Brian在评论中所说的那样,是因为输入被缓冲了。 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. 当您键入a然后按回车键时,回车键将刷新缓冲区,并且您看到循环执行3次。 Once for the first character, a , and twice more for the \\n and \\r characters representing the new line and carriage return characters. 第一个字符为a ,第二个字符为\\n\\r代表新行和回车符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM