如何重试/捕获输入不匹配异常而不会被无限循环捕获
我正在尝试从用户那里获取输入,以构建2d地雷的哭泣游戏的网格,
,当我将有效值传递给Scanner时,过程进行得很顺利,但是当我尝试无效的事情时,过程就进行了通过无限循环,即使try块是try资源,也应该尝试每次重新尝试关闭扫描仪,当它无限期地在catch上打印字符串时,听起来并没有关闭
I'm trying to take input from the user to build a grid for a 2d mine's weeper game, the process goes pretty smooth when I pass valid values to the Scanner, but when I try invalid things it goes through infinite loop even the try block is try with resources which should close the scanner with each a new try, it sounds it doesn't close it when it prints the string on the catch infinitely
int gridSize = 0;
System.out.println("how much do you want the grid's size");
try (Scanner scanner = new Scanner(System.in)) {
while (gridSize == 0) {
gridSize = scanner.nextInt();
scanner.next();
}
} catch (NoSuchElementException e) {
System.out.println("try again");
}
您发现错误了例外-如果输入的不是 int
,则为 InputMismatchException
会被抛出。但是无论如何,使用 hasNextInt()
:
You're catching the wrong exception - if the input isn't an int
, an InputMismatchException
will be thrown. But regardless, this can be made easier by using hasNextInt()
:
try (Scanner scanner = new Scanner(System.in)) {
while (!scanner.hasNextInt()) {
System.err.println("Try again, this time with a proper int");
scanner.next();
}
gridSize = scanner.nextInt();
}