Java, try-catch with Scanner

pavithra picture pavithra · Sep 15, 2015 · Viewed 23k times · Source

I am creating a small algorithm and this is a part of it.

If the user enters non integer values, I want to output a message and let the user enter a number again:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

I am getting a never ending loop and I can't figure out why.

How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?

Update
When I am printing the exception I get 'InputMismatchException', what should I do?

Answer

James Jithin picture James Jithin · Sep 15, 2015

The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc. Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.

boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);

do {
    try {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class
    } catch (InputMismatchException e) {
        sc.next();
        wenttocatch = true;
        System.out.println("xx");
    }
} while (wenttocatch == true);