Dayem Siddiqui
Dayem Siddiqui

Reputation: 215

How do I take input along with handling exceptions?

I want to take an integer input from the user. I am using a try-catch exception so that if the input is not an int it asks the user for another input. I have written the following code:

   while (flag==true) {       
        try {    

            System.out.println("Enter the encryption key!");
            k = input.nextInt();
            flag = false;
        }
        catch (InputMismatchException ex) {
            System.out.println("Please enter integer value!(");


        } 
    }

But when an exception occurs the loop keeps on printing

"Enter the encryption key!"
"Please enter integer value!"

infinitely because the scanner input does not wait to take another input.

How can I tackle with this problem?

Upvotes: 1

Views: 77

Answers (3)

Akash Thakare
Akash Thakare

Reputation: 23012

You should go with suggestion of Maroun Maroun that looks more clean to me.

One other way is to re-initialize the Scanner in loop.

boolean flag = false;
        while (!flag) {       
            try {    
                input = new Scanner(System.in);//Initialize it here
                //....

Upvotes: 1

Kevin
Kevin

Reputation: 46

You could try to use

input.nextLine()

because then it waits until you press enter. But then you need to parse it to an int if i remember correctly.

Upvotes: 1

Maroun
Maroun

Reputation: 96016

You should call next inside the catch clause, this will solve the problem.

See the docs - Scanner:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Without having next in the catch clause, input.nextInt(); will keep reading the same token, adding next will consume that token.

Upvotes: 1

Related Questions