1

I feel like i almost have this right. the error is saying that (!isinputValid) is not initialized. trying to work out why that is and how to change it so my question repeats with invalid inputs (more than 24).

        boolean isInputValid;

        // The license plate must be a string and imported using next(), max 24hr parking
        for (int i = 0; i < licensePlates.length; i++) {
            System.out.println("Auto" + (i + 1));
            System.out.print("      Kenteken: ");
            licensePlates[i] = input.next();
            System.out.print("      Geparkeerde uren (max. 24): ");
            parkingTime[i] = input.nextInt();
            if (parkingTime[i] > 24){       // the max time for parking is 24hr
                isInputValid = false;
                System.out.println("      De parkeerduur kan maximaal 24 uur zijn");
            }
            while (!isInputValid);
        }

    }

}
  • `while (!isInputValid);` this by itself does nothing if `isInputValid` is `true` and goes in an infinite loop if `isInputValid` is `false`. What is that `while` doing there all alone? – Federico klez Culloca Apr 20 '20 at 11:55

1 Answers1

0

Do it as follows:

do {
    isInputValid = true;
    System.out.print("      Geparkeerde uren (max. 24): ");
    try {
        parkingTime[i] = Integer.parseInt(input.nextLine());
        if (parkingTime[i] > 24) { // the max time for parking is 24hr
            isInputValid = false;
            System.out.println("      De parkeerduur kan maximaal 24 uur zijn");
        }
    } catch (NumberFormatException e) {
        isInputValid = false;
    }
} while (!isInputValid);

Also, note that I've used nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72