java.util.Scanner 不返回提示符
import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.next());
}
s.close();
}
}
该程序不会返回提示符(我一直通过终端运行它)。这是为什么?我怎样才能纠正它?
import java.util.Scanner;
class newClass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.next());
}
s.close();
}
}
This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为
s.hasNext()
将阻塞,直到有更多输入可用,并且只有在遇到流末尾时才会返回 false。来自文档:
在 unix 系统上,您可以通过键入 Ctrl+D 来结束流它正确地将控制返回到提示符,(或通过键入 Ctrl+C 终止整个程序)。
您可以
Because
s.hasNext()
will block until further input is available and will only return false if it encounters end of stream.From the docs:
On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).
You can either
System.in.close()
programatically from another thread.这是对上面评论的回复。这里,当收到“quit”时,应用程序将退出。
This is a reply to a comment above. Here, the application will quit when receiving "quit".
扫描仪将阻止等待来自 System.in(标准输入)的输入。您必须按 Ctrl+C 退出程序,按 Ctrl+D 关闭输入流或为循环提供退出条件(例如输入“quit”),以下是执行此操作的方法:
The Scanner will block waiting for input from System.in (standard input). You have to press Ctrl+C to exit the program, close the Input stream by pressing Ctrl+D or give the loop an exit condition (like typing "quit"), here is how you could do that: