My code crashes whenever the user inputs letters. I want to make it so the user can only input whole numbers under 18. If it's under 18 I want to prompt them to "enter a number under 18" and if its a letter prompt them "only enter whole numbers".
I got the under 18 working and above 18 working. I have tried while loops for the letters but it still would crash.
static void intMethod (String vName) {
Scanner intInput = new Scanner(System.in);
System.out.print("Enter "+ vName + ": ");
intStore = intInput.nextInt();
while(tf) {
if (intStore < 18 ) {
tf = false;
}else if(intStore >= 18) {
System.out.println("Please only enter a whole number under 18");
System.out.print("Enter an " + vName + ": ");
intStore = intInput.nextInt();
}else if(!intInput.hasNextInt()){
System.out.println("Please only enter a whole number under 18");
System.out.print("Enter an " + vName + ": ");
intInput.nextLine();
}
}
}
Whenever I try to input letters I get this error message in stacktrace:
Enter age: af
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at IlstueduClass.FunWithMethods.intMethod(FunWithMethods.java:27)
at IlstueduClass.FunWithMethods.main(FunWithMethods.java:56)