how to re-try/catch input mismatch exception without getting caught by infinite loop

馋奶兔 提交于 2019-12-24 03:14:40

问题


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


来源:https://stackoverflow.com/questions/52904629/how-to-re-try-catch-input-mismatch-exception-without-getting-caught-by-infinite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!