D
D
devpy142021-03-21 19:54:57
Java
devpy14, 2021-03-21 19:54:57

Why is Scanner not waiting for user input in the while loop?

I need some number from the user, not a letter. The first time you run the program on the line " firstNum = scanner.nextInt();" the program waits for the user to type something into the console. Suppose the user entered there not what is needed, namely some letters, but then the program endlessly prints on the screen:
"Only numbers, not letters, please
Enter the first number:"
Why is this happening? Why, when the program once again reaches the line " firstNum = scanner.nextInt();", does it not wait for user input?

Scanner scanner = new Scanner(System.in);
        int firstNum;

        while (true) {
            try {
                System.out.println("Enter the first number:");
                firstNum = scanner.nextInt();
                break;
            } catch (InputMismatchException e) {
                System.out.println("\nOnly numbers, not letters, please");
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-03-21
@devpy14

Move Scanner scanner = new Scanner(System.in);it inside the try block: this way it will be re-initialized each time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question