为什么发生异常后Scanner不读取值?这是代码。当抛出异常时,在下一次迭代中它不允许用户输入数据,它总是转到 catch block 并打印文本。
public class Main {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
boolean correctInput = false;
do {
try {
int readInt = inputScanner.nextInt();
correctInput = true;
} catch (InputMismatchException e) {
correctInput = false;
System.out.println("Please enter int value");
}
} while (!correctInput);
}
}
最佳答案
nextInt
不消耗非整数值,因此一旦异常发生,任何此类输入都将无限期地传递到异常 block 。因此你需要消耗这个值
} catch (InputMismatchException e) {
System.err.println("Invalid integer: " + inputScanner.nextLine());
...
}
或者更好的是简单地使用hasNextInt
while (inputScanner.hasNextInt()) {
... // no boolean flag needed
}
关于java - 异常后扫描仪不读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25764828/