我有一个接受用户输入的代码。需要循环来不断询问输入的格式是否不正确。只要输入正确,程序就可以正常运行。 附言。当用户输入错误的输入时,它会失败。
Exception: java.util.NoSuchElementException at java.util.Scanner.nextLine(Unknown Source)
如果我使用BufferedReader
,我没有任何问题。
只有 Scanner
才会失败。
感谢您的任何澄清。
public String getUserInput(String prompt) {
String inputLine = null;
Scanner sc = new Scanner(System.in);
while(true){
inputLine = null;
System.out.println(prompt + " ");
inputLine = sc.nextLine();
if(inputLine.length() == 2 &&
inputLine.charAt(0) >= 'a' && inputLine.charAt(0)<='g' &&
inputLine.charAt(1) >= '0' && inputLine.charAt(1)<='6'){
break;
}
else{
System.out.println("You entered your guess incorrectly.");
System.out.println("Please enter your guesses with ranges a through g and 0 through 6.");
}
}
sc.close();
return inputLine.toLowerCase();
}
最佳答案
您可以通过执行以下操作来检查是否有下一行: sc.hasNext()
如果有则返回 true。您应该在调用 sc.nextLine()
关于java - 从循环中的扫描仪获取异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262551/