Check Scanner number input boundary in Java
In many cases if you want to create an interactive command line interface, you need to check if a number entered by the user is valid and - if it isn’t - you want the user to re-input it.
Here’s a simple static method to check if a number typed by a user is within a given boundary:
/**
* Lets the user input an integer value until it satisfies the given
* conditions
*
* @param msg The prompt to ask the user for the value.
* @param lower The lower boundary, inclusive
* @param upper The upper boundary, inclusive
*/
private static int guardedInput(String msg, int lower, int upper) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(msg);
int val = -1;
try {
val = scanner.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Illegal value: Please type a number!");
}
if (val < lower) {
System.out.println("Illegal value: Must be greater than " + (lower - 1));
} else if (val > upper) {
System.out.println("Illegal value: Must be smaller than " + (upper + 1));
} else {
return val;
}
}
}