![](/img/trans.png)
[英]Java: two threads printing & receiving user input via Scanner: program doesn't exit after exception is thrown
[英]Scanner doesn't read user input after exception
发生异常后,为什么Scanner无法读取该值? 这是代码。 当引发异常时,在下一次迭代中,它不允许用户输入数据,它总是进入catch块并打印文本。
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
不会使用非整数值,因此一旦发生异常,任何此类输入都会无限制地传递给异常块。 因此,您需要消耗此值
} catch (InputMismatchException e) {
System.err.println("Invalid integer: " + inputScanner.nextLine());
...
}
或者更好地使用hasNextInt
while (inputScanner.hasNextInt()) {
... // no boolean flag needed
}
} catch (InputMismatchException e) {
correctInput = false;
System.out.println("Please enter int value");
inputScanner.next();
}
消耗一个令牌并继续
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.