-1

I am stuck in an infinite loop with this piece of code. The program generates endless lines of "Enter number 1> Please enter a number." when an invalid input like "a" is entered instead of an integer. I don't know what's wrong with my boolean variable, everything seems fine to me. Please check it out, thank you so much.

import java.util.*;
public class Adder{
    public static void main(String[] args){

        Scanner sc=new Scanner(System.in);

        boolean correctInput=false;
        while(!correctInput){

            try{

                System.out.print("Enter number 1> ");
                int num1=sc.nextInt();

                System.out.print("Enter number 2> ");
                int num2=sc.nextInt();

                System.out.println("Sum = "+(num1+num2));
                correctInput=true;
            }
            catch(InputMismatchException e){
                System.out.println("Please enter a number.");
                correctInput=false;
            }
        }
    }
}
Arsaceus
  • 295
  • 2
  • 18
Ha Nguyen
  • 1
  • 3
  • 1
    Possible duplicate of [How to handle invalid input using Scanner and try/catch (currently have an infinite loop)](http://stackoverflow.com/questions/3572160/how-to-handle-invalid-input-using-scanner-and-try-catch-currently-have-an-infin) – Tom Feb 03 '16 at 09:14

2 Answers2

3

Add sc.nextLine(); statement in your catch block.

user2004685
  • 8,721
  • 4
  • 29
  • 49
0

If you need to retry then add sc.nextLine(); otherwise you can break the loop as well by putting break; statement in catch block.