I want the user to enter a number that is scanned with the following code:
scanner.nextInt();
If the user enters a string instead, the program throws an InputMismatchException , which is obvious. I want to catch the exception in such a way that the program will prompt the user to enter input until the user enters an integer value.
Scanner scanner = new Scanner(System.in); while(true) { try { System.out.println("Please enter a number: "); int input = scanner.nextInt(); System.out.println(input);
This code creates an endless loop if a string is entered.
source share