1

Im trying to create a simple program where user enters an integer and if its not an integer it prints that an error occured and the program loops until user enters an integer. I found this try-catch solution but it doesn`t work properly. If user doesnt enter an integer the program will infinitly loop.

What would the correct solution be?

Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while(isInt == false)
{
    System.out.println("Enter a number:");
    try
    {
        number = input.nextInt();
        isInt = true;
    }
    catch (InputMismatchException error)
    {
        System.out.println("Error! You need to enter an integer!");
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

You're close.

It's easier to fail on parsing a string than it is to try to get an int from the Scanner since the scanner will block until it gets an int.

Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while (isInt == false) {

    System.out.println("Enter a number:");
    try {
        number = Integer.parseInt(input.nextLine());
        isInt = true;
    } catch (NumberFormatException error) {
        System.out.println("Error! You need to enter an integer!");
    }

}
Makoto
  • 104,088
  • 27
  • 192
  • 230