我有一个循环,在从控制台接收到正确的输入后会中断。我正在使用 Scanner 从 System.in 读取字符串,这似乎给我带来了麻烦。这是我的代码:
boolean loop = true;
while(loop) {
try {
System.out.println("Enter an input (\"input a\" or \"input b\"): ");
String input = scanner.nextLine();
System.out.println("");
if (input.equals("input a")) {
System.out.println("Answer to input a.");
} else if (input.equals("input b")) {
System.out.println("Answer to input b.");
} else {
throw new IllegalArgumentException();
}
loop = false;
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
System.out.println("");
} catch (IllegalArgumentException e) {
System.out.println("Input not recognized. Please enter a valid input.");
System.out.println("");
}
}
当调用它时,它会循环一次,甚至不等待用户的输入,然后实际上停止并执行第二次应该执行的操作。 IE,在用户根本不提供任何输入的情况下,其输出是:
Enter an input ("input a" or "input b"):
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"):
如果我给它一个错误的输入(以便它循环并再次询问),它会执行相同的操作,在等待之前循环两次。我不知道为什么。
为什么会发生这种情况,我应该怎样做才能避免这种情况?
编辑:hasNext 检查后的测试场景:
场景A:
Enter an input ("input a" or "input b"): input a //my input
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): //no input given here
Answer to input a.
场景B:
Enter an input ("input a" or "input b"): ddd //my input
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): //no input given here
Input not recognized. Please enter a valid input.
Enter an input ("input a" or "input b"): input b //my input
Answer to input b.
产生这个的代码:
boolean loop = true;
while(loop) {
if (scanner.hasNext()) {
try {
System.out.println("Enter an input (\"input a\" or \"input b\"): ");
String input = scanner.nextLine();
System.out.println("");
if (input.equals("input a")) {
System.out.println("Answer to input a.");
} else if (input.equals("input b")) {
System.out.println("Answer to input b.");
} else {
throw new IllegalArgumentException();
}
loop = false;
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
System.out.println("");
} catch (IllegalArgumentException e) {
System.out.println("Input not recognized. Please enter a valid input.");
System.out.println("");
}
}
}
最佳答案
我尝试了您在问题中写下的代码,作为一个问题,但我根本找不到任何问题。不过,我想我知道答案。
如果您在此之前使用原始类型或仅使用 next() 进行了任何其他输入,则需要刷新不幸的是这些 next 方法留下的换行符。为此,只需在方法返回输入字符串并将其分配给 input 的语句之前调用“scanner.nextLine()”即可。
您要确保单独调用该方法;你知道,就其本身而言。最好在输入之前将其放入顶部的 while 循环中,这样每次迭代时都会清除换行符。然后该语句将删除换行符,因此输入缓冲区为空。一旦清除,您终于可以在第一次循环迭代时输入字符串。
这个答案怎么样?尝试一下,如果有效请告诉我!
关于Java Scanner 接收不存在的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21963232/