所以我希望我的程序读取一个输入,其中一行中有一些整数,例如:
1 1 2
然后它应该单独读取每个整数并将其打印在新行中。程序必须读取的整数数量没有提前给出,所以我想做的是使用 while 循环,该循环在没有更多整数可供读取后结束。这是我写的代码:
while (scan.hasNextInt()) {
int x = scan.nextInt();
System.out.println(x);
}
但它无法正常工作,因为循环永远不会结束,它只是希望用户输入更多整数。我在这里缺少什么?
The hasNextInt
call blocks直到它有足够的信息来做出“是/否”的决定。
Press Windows 上的 Ctrl+Z(或“unix”上的 Ctrl+D) https://stackoverflow.com/questions/16136400/how-to-send-eof-via-windows-terminal关闭标准输入流 http://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29并触发EOF http://en.wikipedia.org/wiki/End-of-file。或者,输入非整数并按回车键.
控制台输入通常是行缓冲的:必须按下 Enter 键(或触发 EOF),整行将立即处理.
示例,其中 ^Z 表示 Ctrl+Z(或 Ctrl+D):
1 2 3<enter>4 5 6^Z -- read in 6 integers and end because stream closed
-- (two lines are processed: after <enter>, after ^Z)
1 2 3 foo 4<enter> -- read in 3 integers and end because non-integer found
-- (one line is processed: after <enter>)
也可以看看:
- 如何让 Java 的 hasNextInt() 停止等待整数而不输入字符? https://stackoverflow.com/questions/7613526/how-do-i-get-javas-hasnextint-to-stop-waiting-for-ints-without-inputting-a-ch
- hasNext() - 它何时阻塞以及为什么? https://stackoverflow.com/questions/16873134/hasnext-when-does-it-block-and-why
- Java Scanner hasNext() 不返回 false https://stackoverflow.com/questions/15847036/java-scanner-hasnext-doesnt-return-false
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)