How to prevent users from entering anything but int

2765 views java
6

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!");
    }
}

answered question

1 Answer

13

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!");
    }

}

posted this

Have an answer?

JD

Please login first before posting an answer.