Skip to content

Instantly share code, notes, and snippets.

@Pzdrs
Created February 24, 2022 19:47
Show Gist options
  • Select an option

  • Save Pzdrs/1278a937e9a8e3ff6d5b43ca6a3f0710 to your computer and use it in GitHub Desktop.

Select an option

Save Pzdrs/1278a937e9a8e3ff6d5b43ca6a3f0710 to your computer and use it in GitHub Desktop.
Prompt the user for and integer - validation included
/**
* Prompt the user for and integer
*
* @param message Prompt message
* @param range The range the integer is suppose to be in
* @return Validated integer
*/
public static int promptNumericInt(String message, Map.Entry<Integer, Integer> range) {
boolean error = true;
int value = 0;
do {
try {
System.out.print(message);
value = scanner.nextInt();
if (!inRange(value, range.getKey(), range.getValue())) {
System.out.println("Value out of range");
continue;
}
error = false;
} catch (InputMismatchException exception) {
scanner.next();
System.out.println("Not a number");
}
} while (error);
return value;
}
/**
* Prompt the user for and integer - the whole domain is considered (no upper or lower limits)
*
* @param message Prompt message
* @return Integer
*/
public static int promptNumericInt(String message) {
return promptNumericInt(message, new AbstractMap.SimpleEntry<>(Integer.MIN_VALUE, Integer.MAX_VALUE));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment