非终止 Java 程序
我有这个与 Java 输入相关的问题。 我正在 UVAToolkit 中解决一些情况,但是存在一些问题,行输入需要从 System.in 中获取。根据下面的这些代码,按下按键后如何终止问题?下面显示了示例输入/输出。
Scanner scanner = new Scanner(System.in);
String line;
while((line = scanner.nextLine()) != null) {
System.out.println(line);
}
System.out.println("done");
示例输入:
1 10
10 100
100 1000
示例输出:
1 10
10 100
100 1000
done
提前致谢。
I have this Java input-related problem.
I'm solving some cases in UVAToolkit, but there are some problems that the line input requires from the System.in. Basing from these codes below, how could I terminate the problem once I've pressed key? The sample input/output are displayed below.
Scanner scanner = new Scanner(System.in);
String line;
while((line = scanner.nextLine()) != null) {
System.out.println(line);
}
System.out.println("done");
Sample Input:
1 10
10 100
100 1000
Sample Output:
1 10
10 100
100 1000
done
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不检查空输入,而是检查空字符串。这样,您应该只需按回车键即可终止。
Don't check for null input but for an empty string. This way, you should be able to terminate just by pressing the return key.
要结束输入,应该先按 ctrl+d,否则
scanner.nextLine()
不会返回 null,而是挂起。例如,如果您想在输入
quit
后退出应用程序,您可以执行以下操作:To end the input, you should pree ctrl+d, otherwise,
scanner.nextLine()
will not return null, but hang.if you want to quit the application once the word
quit
entered for example, you can do:使用像
STOP\n
这样的哨兵值或关闭流。对于 Windows(我猜)按 ctrl +z ,对于 Linux 按 ctrl + d 来关闭流。Either use sentinel value like
STOP\n
or close the stream. Press ctrl +z for windows(i guess) and ctrl + d for Linux to close the stream.您可以决定一个特殊的字符串来结束循环,并检查这个特殊的字符串。例如:
You could decide on a special string that will make the loop end, and check for this special string. For example:
尝试检查空行而不是 null:
Try checking for an empty line instead of null: