0

I'm simply want to get a valid int value for age

But when user enters an string, why i cant get an int again?

Here is my code:

public static void getAge() throws InputMismatchException {

    System.out.print("Enter Your age: ");
    try {
        age = in.nextInt();
    } catch (InputMismatchException imme) {
        System.out.println("enter correct value for age:");
        in.nextInt(); // why this not works?
    }
}

Enter Your age: hh
enter correct value for age:
Exception in thread "main" java.util.InputMismatchException

I want to request to enter a valid int value until a valid input enters.

StackFlowed
  • 6,575
  • 1
  • 26
  • 41

1 Answers1

1

If nextInt() fails to parse the input as an int, it leaves the input in the buffer. So the next time you call nextInt() it is trying to read the same garbage value again. You must call nextLine() to eat the garbage input before trying again:

System.out.print("Enter your age:");
try {
    age = in.nextInt();
} catch (InputMismatchException imme) {
    System.out.println("Enter correct value for age:");
    in.nextLine(); // get garbage input and discard it
    age = in.nextInt(); // now you can read fresh input
}

You probably want to arrange this in a loop too, so that it will keep asking repeatedly so long as the input is unsuitable:

System.out.print("Enter your age:");
for (;;) {
    try {
        age = in.nextInt();
        break;
    } catch (InputMismatchException imme) {}
    in.nextLine();
    System.out.println("Enter correct value for age:");
}
Boann
  • 44,932
  • 13
  • 106
  • 138