简体   繁体   English

Java Scanner hasNextInt()导致无限循环

[英]Java Scanner hasNextInt() causing infinite loop

What I am trying to do is have the user enter a lot of numbers and then hit enter, and then store all those numbers onto a stack at once. 我想做的是让用户输入很多数字,然后按Enter,然后将所有这些数字立即存储到堆栈中。 My thought was to use a loop to go through all the numbers and push them onto the stack like so: 我的想法是使用循环遍历所有数字并将其推入堆栈,如下所示:

Stack<Integer> mainBin = new Stack<Integer>();

Scanner scanner = new Scanner(System.in);

while (scanner.hasNextInt()) {          
mainBin.push(scanner.nextInt());
}

However, even after I press enter many times without entering anything new, it still stays in the loop. 但是,即使我多次按Enter键却没有输入任何新内容,它仍然停留在循环中。 Any suggestions? 有什么建议么?

Scanner.hasNextInt() skips over whitespace to find the next token. Scanner.hasNextInt()跳过空白以查找下一个标记。 So it reads and skips over all your Enter presses. 因此,它会读取并跳过所有Enter键。 Then it waits for more input, because there may be more input coming. 然后它等待更多的输入,因为可能会有更多的输入。

In a Linux terminal, you can press Ctrl-D (maybe Cmd-D on OS X?) to send an end-of-file marker, which tells the application that there is no more input coming (this should be done at the start of a line). 在Linux终端中,您可以按Ctrl-D (也许是OS X上的Cmd-D ?)来发送文件结束标记,该标记告诉应用程序不再有输入(这应该在开始时完成)线)。 This answer suggests that Ctrl-Z is the equivalent in Windows' command prompt. 该答案表明Ctrl-Z在Windows的命令提示符中等效。

Alternatively, you could have some special input that your application reads. 另外,您可能需要应用程序读取一些特殊的输入。 @phatfingers commented that you could specify the number of values to read as the very first input. @phatfingers评论说,您可以指定要读取的值的数量作为第一个输入。 You could also have a special value to signify the end (0 or -1 are common choices, based on the application's needs), or maybe even use a non-numeric token like "end". 您也可以使用一个特殊的值来表示结束(根据应用程序的需要,0或-1是常见选择),甚至可以使用诸如“ end”之类的非数字标记。

Your example uses scanner.hasNext() . 您的示例使用scanner.hasNext() Use scanner.hasNextInt() instead. 请改用scanner.hasNextInt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM