-1
public static void main(String[] args) {

    int age=0 ;
    while(age == 0) {
        System.out.println("How old are you");
        age = checkValidAge();
    }
                
    }

    public static int checkValidAge() {
        try {
            return userInput.nextInt();
        }
        catch(InputMismatchException e) {
            userInput.next();
            System.out.println("Enter a interger");
            return 0;
        }
    }

}

Started learning java recently(complete beginner).
So I am bit confused, when I input numbers this cause loop to break and when I enter characters loop dont break so isn't meant to be other way around.
Just wanted to create something that catches the error and lets you try again.

s3cret
  • 354
  • 2
  • 10

2 Answers2

0

As your code writes:
while (age == 0)
When your your input is

  • Integer (which isn't equal to 0), let's say 3:
    function checkValidAge() return 3 and assign 3 to age,
    since the local variable age = 3, it will of course break the while loop because a == 0 is false;
  • Character
    You input a character, and function checkValidAge() will raise InputMismatchException, and the checkValidAge() return value is 0.
    Then the return value 0 is assigned to the local variable age, which means age = 0. At this time, age == 0 returns true, and meets the requirments for the while loop to continue.
s3cret
  • 354
  • 2
  • 10
0

No, it is the right way around. The whole idea of the prompt loop is to get a valid Integer value. If the supplied data is invalid then the User is informed and the 0 is returned from the validation method so that the prompt loop continues and provides the User with the same prompt in order to try again.

Since validation is to be carried out on the User's input then perhaps you should go all the way with it for this particular Age prompt. There are a lot of integers that can be supplied which should be considered invalid such as:

  • Any signed value (ex: -63);
  • Any unsigned value under a reasonable minimum age: (ex: 18). How old will the User need to be in order to use your application. Will a 1 year old use your app?
  • Any unsigned value over a reasonable maximum age: (ex: 125). The oldest person ever on this planet lived to be 122 years old.

You may want to add a inclusive value range to your checkValidAge() method:

public static int checkValidAge(int min, int max) {
    int ageValue = 0;
    try {
        ageValue = userInput.nextInt();
        if (ageValue < min || ageValue > max) {
            throw new InputMismatchException();
        }
    }
    catch(InputMismatchException e) {
        System.out.println("Invalid age supplied! (" + ageValue + ")");
        ageValue = 0;
    }
    
    userInput.nextLine();       // consume ENTER
    return ageValue;
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22