问题描述
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();
}
}
只是想知道在我完成输入后如何终止程序?由于假设我将继续输入输入,扫描仪在几次Enter"后仍会继续...我试过了:
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 和 Mac OS 上(通常)+,在 Windows 上 +.这将导致
hasNextLine()
返回false
.
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) +, and on Windows +. That will result in
hasNextLine()
returningfalse
.
输入一些被程序识别为我完成了"的特殊输入.例如,它可以是一个空行,或者一些特殊的值,比如exit".程序需要专门为此进行测试.
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.
您当前版本失败的原因是您使用 ==
来测试空字符串.您应该使用 equals
或 isEmpty
方法.(请参阅如何比较 Java 中的字符串?)
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").
这篇关于输入完成后如何终止扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!