I am trying to write a program to ask a user to enter their age and prompt them to re-enter if they enter an improper value (such as a negative number, older than 120, an age with special characters or letters, an out of range number etc...)
I tried writing a try/catch to ask the user to re-enter their age:
System.out.println("Enter your age (a positive integer): ");
int num;
try {
num = in.nextInt();
while (num < 0 || num > 120) {
System.out.println("Bad age. Re-enter your age (a positive integer): ");
num = in.nextInt();
}
} catch (InputMismatchException e) {
//System.out.println(e);
System.out.println("Bad age. Re-enter your age (a positive integer): ");
num = in.nextInt();
}
When the age entered contains special characters/letters or is out of range, the program DOES print out the words "Bad age. Re-enter your age (a positive integer)," however it immediately terminates thereafter with this error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at Age.main(Age.java:21)
My goal is to get the program to continue prompting for a valid age until the user gets its right. I would really appreciate any feedback and help. I am a java beginner :) Thank you
I tried to change put the whole code into a while loop but then it causes an infinite loop... please help!
while (num < 0 || num > 120) {
try {
System.out.println("Bad age. Re-enter your age (a positive integer): ");
num = in.nextInt();
} catch (InputMismatchException e) {
System.out.println("Bad age. Re-enter your age (a positive integer): ");
}
}