Using Scanner in Java to read input from user until Integer is found



This is an example of getting user input and looping as long as the input is not an integer.
This is done by using the Scanner class and sending System.in as parameter to the constructor. Then we declare a boolean and use that in the while loop to continue the loop as long as the loop is equal to true.
We call the next() method of the Scanner instance which will wait until user types something and hit the enter key. The we use Integer.parseInt on the input value. The code is put in a try-block which has a corresponding catch-block. If the input is not an integer value a NumberFormatException will be thrown, and caught in the catch-block, and the loop will continue to print out a message for the user to enter a value.
If the input is an integer value no exception will be thrown and the boolean flag (keepLooping) will be set to false and the loop will exit.

Possible output from the code above:







Search for more Java info on this site here:
Custom Search


Please type any questions here.