首页 > 解决方案 > My loop with try catch is stuck in endless loop and it should prompt the user each time for an input

问题描述

I'm trying to ask the user for a number and if they enter anything wrong (not an int between 1 and 99) then catch (to prevent crash if string) and loop until enter a right number. My loop is stuck in an endless loop somehow. Note: I do have the Scanner imported and the exception imported too.

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String result;
        int number;
        boolean done = false;
        while (true) {
            try {
                System.out.println("Please select a number from 1 to 99.");
                number = input.nextInt();
                input.nextLine();

                if (number >= 1 || number <= 99) {
                    result = checkNumber(number);
                    System.out.println(result);
                    break;
                }
            } catch (InputMismatchException exception) {
            }
        }
    }

标签: javawhile-looptry-catch

解决方案


input.nextInt() won't consume anything not an int. It will throw an exception. You ignore the exception and try to consume an int. It's still not an int. Same exception. Infinite loop. Add another input.nextLine() in your catch block.


推荐阅读