Java扫描器hasNext()不会返回false [英] Java Scanner hasNext() doesn't return false
问题描述
我正在尝试从用户连续读取输入,直到用户键入退出为止.我只是通过输入"quit"来测试它,但是console.hasNext()似乎没有返回false.实际上,似乎该程序在第7行(hasNext()行)上被阻止.有什么想法吗?
I am trying to read input continuously from the user until the user types quit. I am testing it by just typing 'quit' but console.hasNext() doesn't seem to be returning false. In fact it seems that the program is blocked on line 7(hasNext() line). Any ideas?
boolean bool = true;
while (bool) {
System.out.println("Type 'quit':");
Scanner console = new Scanner(System.in);
if (console.next().equals("quit")) {
System.out.println("You typed quit");
System.out.println("check: " + console.hasNext()); // This line doesnt print
bool = false;
}
}
推荐答案
如果将Scanner
声明为System.in
,它将询问System.in
是否要接收下一个值.然后,in
类将等待用户输入某些内容,然后返回true.
If your Scanner
is declared as System.in
, it will be asking System.in
if there is a next value to be received. The in
class will then wait for the user to input something, then return true.
为文件之类的内容保留hasNext()
,其中输入大小是固定的.这样,当Scanner
查询文件时,它就有一个确定的hasNext()
.
Reserve hasNext()
for things like files, where the input size is fixed. That way, when Scanner
queries the file, it has a definite hasNext()
.
相反,我建议使用字符串作为下一个值,然后检查它是否与整数格式匹配.如果是这样,则将其转换,否则,请根据需要进行处理.
Instead, I suggest grabbing the next value as a String, then checking if it matches the integer format. If it does, then convert it, otherwise, handle it however you'd like.
这篇关于Java扫描器hasNext()不会返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!