Scanner tiene consigo métodos que ya detectan si la siguiente entrada tiene el formato que se busca. En este caso como es lectura de enteros usamos scanner.hasNextInt
Internamente scanner.hasNextInt
valida con REGEX y con try catch
import java.util.Scanner;
public class Main {
// Tiene el modificador private puesto que en este ejemplo sólo se usará en esta clase
// Tanto scanner como el método son estáticos para que puedan ser accesados dentro del Main (otro contexto estático)
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number1 = readNumber(0, 120, "Please enter a valid number: ");
int number2 = readNumber(Integer.MIN_VALUE, Integer.MAX_VALUE, 2, "Please enter other valid number in binary form: ");
// Impresión con formato
System.out.printf("%s %d, %d", "You entered the next numbers: ", number1, number2);
}
/**
* This method will read a integer decimal number
* @param min min integer value accepted
* @param max max integer value accepted
* @param msg the message that will be displayed for asking the entrance
* @return a integer number between max and min read from STDIN
*/
public static int readNumber(int min, int max, String msg) {
return readNumber(min, max, 10, msg);
}
/**
* @param min min integer value accepted
* @param max max integer value accepted
* @param radix radix of the input
* @param msg the message that will be displayed for asking the entrance
* @return a integer number between max and min read from STDIN
*/
private static int readNumber(int min, int max, int radix, String msg) {
int number;
while (true) {
System.out.println(msg);
// Si lo siguiente en el búfer no es entero entonces:
if (!scanner.hasNextInt(radix)) {
System.err.println("Invalid entrance\nThe entrance must be a integer number");
// Limpiando la entrada inválida
scanner.nextLine();
continue;
}
// Se lee el entero y se limpia el búfer sobrante por si acaso
number = scanner.nextInt(radix);
scanner.nextLine();
// Validación máximo y mínimo
if ( number < min || number > max ) {
System.err.printf(
"%s %d %s %d, %s",
"Invalid number\nThe number must be between", min,
" and ",
max,
" (inclusive).\n"
);
continue;
}
return number;
}
}
}
Así se ve el método de hasNextInt
de acuerdo al OPENJDK 15 e IntelliJ
public boolean hasNextInt(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
try/catch
es para manejar errores "excepcionales" que no pueden anticiparse en la ejecución del programa. En este caso lo práctico es leer la entrada del usuario como una cadena, validar que esa cadena represente un entero y luego hacer la conversión a tipo entero.