I want the output of the program to return to the question if the user inputs a wrong value.

This is for my homework. I've tried to search on Youtube and Google, but I can't identify my error and didn't show what is my error.

final int MINS_IN_AN_HOUR = 60;
final int AN_HOUR = 100;
final int LAST_MINUTE_OF_A_DAY = 2359;
int arrivalTime = 0;
int arrivalMins = 0;
Scanner input = new Scanner(System.in);

System.out.print("Please enter the vehicle's arrival time (24-hour format): ");
    while(true){
    arrivalTime = input.nextInt();
       if(arrivalTime >= AN_HOUR && arrivalTime <= LAST_MINUTE_OF_A_DAY){
          int hours = arrivalTime / AN_HOUR;  
          int minutes = arrivalTime - hours * AN_HOUR;   
          arrivalMins = hours * MINS_IN_AN_HOUR + minutes;  
          break;  // If user was correct, exit program
       }
       else{
          System.out.println("Please enter a valid number or enter a valid time");
          System.out.print("Please enter the vehicle's arrival time (24-hour format): ");

} }

The expected output must be the else statement and repeat the loop.

1 Answers

1
Paul Lemarchand On

The problem in your code is not your condition, the problem is that you are reading the user input using nextInt(), without catching the exception in case the user input is not an int.

Simply replace this line:

arrivalTime = input.nextInt();

with a try...catch block

try {
    arrivalTime = input.nextInt();
} catch(InputMismatchException e) {
    arrivalTime = -1; // will trigger your else status
}