how to re-try/catch input mismatch exception witho

2019-07-13 12:45发布

问题:

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

回答1:

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