Hey guys I have the following while loop which seems not to stop. It’s supposed to ask the user for an hour. I’m trying to catch the event where the user does not enter a number.
i.e.
Enter hour: foo
You did not enter a valid value
It should then allow the user to enter a value for hour again, but it keeps printing the error message over and over
private static void setTime(Clock clock){
int hours = -1;
int minutes = -1;
int seconds = -1;
Scanner scanner = new Scanner(System.in);
while(true)
{
try{
System.out.print("Enter hours: ");
hours = scanner.nextInt();
}
catch(NumberFormatException nfe){
System.out.println("Input was not an integer, please try again");
continue;
}
catch(InputMismatchException ims){
System.out.println("Input was not an integer, please try again");
continue;
}
break;
}
}
Move
Scanner scanner = ...into the while loop.