Non-terminating Java program

大城市里の小女人 提交于 2019-12-12 02:45:28

问题


I have this Java input-related problem. I'm solving some cases in UVAToolkit, but there are some problems that the line input requires from the System.in. Basing from these codes below, how could I terminate the problem once I've pressed key? The sample input/output are displayed below.

Scanner scanner = new Scanner(System.in);
String line;
while((line = scanner.nextLine()) != null) {
    System.out.println(line);
}
System.out.println("done");

Sample Input:

1 10
10 100
100 1000

Sample Output:

1 10
10 100
100 1000
done

Thanks in advance.


回答1:


Don't check for null input but for an empty string. This way, you should be able to terminate just by pressing the return key.

while(!(line = scanner.nextLine()).equals(""))



回答2:


To end the input, you should pree ctrl+d, otherwise, scanner.nextLine() will not return null, but hang.

if you want to quit the application once the word quit entered for example, you can do:

Scanner scanner = new Scanner(System.in);
String line;
while((line = scanner.nextLine()) != null && !line.equalsIgnoreCase("quit")) {
    System.out.println(line);
}
System.out.println("done");



回答3:


Either use sentinel value like STOP\n or close the stream. Press ctrl +z for windows(i guess) and ctrl + d for Linux to close the stream.




回答4:


You could decide on a special string that will make the loop end, and check for this special string. For example:

while((line = scanner.nextLine()) != null) {
    if (line.equals("quit") break;
    System.out.println(line);
}
System.out.println("done");



回答5:


Try checking for an empty line instead of null:

while((line = scanner.nextLine()).isEmpty()) {
    System.out.println(line);
}


来源:https://stackoverflow.com/questions/8062749/non-terminating-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!