-1

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.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • Looks ok at first glance. What exactly happens? – Michael Butscher Jun 02 '19 at 04:38
  • I typed string "error" then it must be a loop to else statement Here's the output: Please enter the vehicle's arrival time (24-hour format): error Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at Calculate_Parking_Fee.Parking_Fee.main(Parking_Fee.java:88) – Diana Mae Bautista Jun 02 '19 at 04:43
  • when I execute your code I got this output: Please enter the vehicle's arrival time (24-hour format): Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at HelloWorld.main(HelloWorld.java:15) – fahime Jun 02 '19 at 04:47
  • 3
    This is expected behavior if the `Scanner` is asked for an `int` but doesn't get one. You should place a `try .. catch` around the `nextInt()` and `continue` in the `catch`. – Michael Butscher Jun 02 '19 at 04:50
  • Thanks for your help! I'd really appreciate it – Diana Mae Bautista Jun 02 '19 at 05:19

1 Answers1

2

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
}
Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27