如何重试/捕获输入不匹配异常而不会被无限循环捕获

时间:2018-10-20 10:24:15

标签: java exception java.util.scanner

我正在尝试从用户那里获取输入,以为2d地雷的哭泣游戏构建网格, 当我将有效值传递给Scanner时,该过程进行得很顺利,但是当我尝试无效的事情时,它会经历无限循环,即使try块是try资源,它每次尝试都应关闭扫描仪后,才尝试关闭资源,听起来好像没有当它无限地在锁扣上打印字符串时,将其关闭

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");
    }

1 个答案:

答案 0 :(得分:0)

您捕获了错误的异常-如果输入不是int,则会抛出InputMismatchException。但是无论如何,可以使用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();
}