问题描述
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
我想知道如何在我拥有程序后终止程序完成输入输入?
由于扫描仪在几次输入之后仍然会继续,假设我要继续输入输入...
我试过:
Just wondering how I can terminate the program after I have completed entering the inputs?As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...I tried:
if (scan.nextLine() == null) System.exit(0);
和
if (scan.nextLine() == "") System.exit(0);
他们没有工作......程序继续并且与初衷混淆,
They did not work.... The program continues and messes with the original intention,
推荐答案
问题是程序(像你的程序)不知道用户已完成输入输入,除非用户......某种程度。 ..告诉它。
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
用户有两种方法可以做到这一点:
There are two ways that the user could do this:
-
输入文件结束标记。在UNIX上(通常) + ,在Windows上 + 。这将导致
hasNextLine()
返回false
。
Enter an "end of file" marker. On UNIX that's (typically) +, and on Windows +. That will result in
hasNextLine()
returningfalse
.
输入一些程序识别为我已完成的特殊输入。例如,它可能是一个空行,或某些特殊值,如退出。该程序需要专门测试。
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
您当前版本失败的原因是您使用 ==
来测试空字符串。您应该使用等于
或 isEmpty
方法。 (请参阅)
The reason your current version is failing is that you are using ==
to test for an empty String. You should use either the equals
or isEmpty
methods. (See How do I compare strings in Java?)
其他内容考虑是区分大小写(例如退出与退出)以及前导或尾随空格的影响(例如退出与退出)。
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
这篇关于输入完成后如何终止扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!