Prompt for input after throwing an exception

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); //statements break; } catch(InputMismatchException | NumberFormatException ex ) { continue; } } 

This code creates an endless loop if a string is entered.

+6
source share
3 answers

Put Scanner scanner = new Scanner(System.in); into the while .

 Scanner scanner; while(true) { try { System.out.println("Please enter a number: "); scanner = new Scanner(System.in); int input = scanner.nextInt(); System.out.println(input); //statements break; } catch(InputMismatchException | NumberFormatException ex ) { System.out.println("I said a number..."); } } 
+4
source

The answer to my problem is as follows:

 Scanner scanner = new Scanner(System.in); while(true) { try { System.out.println("Please enter a number: "); int input = scanner.nextInt(); System.out.println(input); //statements break; } catch(InputMismatchException | NumberFormatException ex ) { scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input continue; } } 
+3
source

How about this?

 while(true) { try { System.out.println("Please enter a number: "); Scanner scanner = new Scanner(System.in); int input = scanner.nextInt(); System.out.println("\n\nEntered number is : " + input); break; } catch(InputMismatchException | NumberFormatException ex ) { System.out.println("\n\nInput was not a number. Please enter number again : "); } catch(Exception e ) { System.out.println("\n\nException caught :: " + e); } } 

I also removed the continue syntax as they are not needed.

0
source

Source: https://habr.com/ru/post/924143/


All Articles