0
votes

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) {
            }
        }
    }
1
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.Elliott Frisch
Wow. such an easy fix. Thank you so much! I think you helped me on my last question too the other day!! Many thanks! :)jrob11

1 Answers

0
votes

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.