5.14 Min and Max Challenge
Time for the next challenge: write a Java program that reads numbers from the console and, when the user enters an invalid value, exits the loop and prints the minimum and maximum number entered. For example, if the user types 5, 3 and 2, the minimum should be 2 and the maximum should be 5. Before each input, the program prompts "Enter a number". Use the Scanner class from the previous lessons.
The solution step by step
- Create the
Scannerand remember to callscanner.close()at the end. - Declare two variables:
int min = Integer.MAX_VALUE;andint max = Integer.MIN_VALUE;. Starting from the extremes guarantees that the first valid input replaces them. - Use an infinite loop
while (true) { ... }. To exit it as soon as the input is invalid, use abreak.
Inside the loop, prompt the user, then check the type with boolean isAnInt = scanner.hasNextInt();. If isAnInt is false, we break out. Otherwise we read the value with int number = scanner.nextInt(); and update the bounds: if (number > max) max = number; and if (number < min) min = number;.
After the loop, we print the final minimum and maximum. Running the program and feeding it several numbers shows the values being updated as expected, until a letter or any non-integer breaks the loop and reveals the result. This pattern of "loop until invalid" combined with hasNextInt is a small but solid foundation for interactive Java console apps.