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?
因为 s.hasNext()
将阻塞,直到有更多输入可用,并且只有在遇到流末尾时才会返回 false。
来自文档:
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.
在 unix 系统上,您可以通过键入 Ctrl+D 来结束流,这会正确地将控制返回到提示符,(或者通过键入 终止整个程序Ctrl+C)。
How can I correct it?
你可以
- 按照 JJ 的建议,保留一些用于终止程序的输入字符串,或者
- 您可以依赖用户使用 Ctrl+D 关闭输入流,或者您也可以
- 将循环包含在 try/catch 中,并让另一个线程中断主线程,然后主线程正常退出。
- 从另一个线程以编程方式执行
System.in.close()
。
关于java.util.Scanner 不返回提示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7107432/