Java 输入完成后如何终止扫描仪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16206813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to terminate Scanner when input is complete?
提问by user2318175
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:
只是想知道在完成输入后如何终止程序?由于假设我将继续输入输入,扫描仪在几次“Enter”后仍会继续......我尝试过:
if (scan.nextLine() == null) System.exit(0);
and
和
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
他们没有工作......程序继续并与初衷一团糟,
采纳答案by Stephen C
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:
用户可以通过两种方式执行此操作:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. 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.
输入“文件结束”标记。在 UNIX 和 Mac OS 上(通常)为CTRL+ D,在 Windows CTRL+ 上Z。这将导致
hasNextLine()
返回false
.输入一些被程序识别为“我完成了”的特殊输入。例如,它可能是一个空行,或一些特殊值,如“exit”。程序需要专门为此进行测试。
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that's not a user-friendly way to do this.)
(您也可以想象使用计时器,并假设用户在 N 秒或 N 分钟内没有输入任何输入就已经完成。但这不是用户友好的方式。)
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?)
您当前版本失败的原因是您正在==
用于测试空字符串。您应该使用equals
或isEmpty
方法。(请参阅如何比较 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").
其他要考虑的事情是区分大小写(例如“退出”与“退出”)和前导或尾随空格的影响(例如“退出”与“退出”)。
回答by user2318175
With this approach, you have to explicitly create an exit command or an exit condition. For instance:
使用这种方法,您必须明确创建退出命令或退出条件。例如:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals()
not ==
. ==
compares the addresses of two strings, which, unless they're actually the same object, will never be true.
此外,您必须使用.equals()
not处理字符串等于情况==
。==
比较两个字符串的地址,除非它们实际上是同一个对象,否则永远不会为真。
回答by Shobit
String comparison is done using .equals()
and not ==
.
字符串比较是使用.equals()
和 not完成的==
。
So, try scan.nextLine().equals("")
.
所以,试试scan.nextLine().equals("")
。
回答by nchouhan
You will have to look for specific pattern which indicates end of your input say for example "##"
您将不得不寻找指示输入结束的特定模式,例如“##”
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}
回答by Jason
In this case, I recommend you to use do, while loop instead of while.
在这种情况下,我建议您使用 do、while 循环而不是 while。
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.
为了退出程序,您只需要分配一个字符串标题,例如退出。如果输入等于退出,则程序将退出。此外,用户可以按 control + c 退出程序。
回答by JDGuide
You can check the next line of input from console, and checks for your terminate entry(if any).
您可以从控制台检查下一行输入,并检查您的终止条目(如果有)。
Suppose your terminate entry is "quit" then you should try this code :-
假设您的终止条目是“退出”,那么您应该尝试以下代码:-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.
试试这个代码。当你想关闭/终止扫描仪时,你的终止行应该由你输入。
回答by clearlight
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int
is a double
produces a double
result so you can avoid some casting by declaring things carefully. Also assigning an int
to something declared double
also implies you want to store it as a double so no need to cast that either.
这是我将如何做到的。说明使用常量来限制数组大小和条目数,双精度除以 anint
是double
一个double
结果,因此您可以通过仔细声明来避免一些强制转换。此外,将 an 分配int
给声明的内容double
也意味着您希望将其存储为双精度值,因此也无需强制转换。
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}