When a user types text where nextInt() expects a number, Java throws an InputMismatchException. Without handling, your program crashes. Here is how to ask repeatedly until the input is valid:
Scanner scanner = new Scanner(System.in);
int age = 0;
boolean valid = false;
while (!valid) {
System.out.print("Enter age: ");
try {
age = scanner.nextInt();
valid = true;
} catch (InputMismatchException e) {
System.out.println("Not a number");
scanner.nextLine();
}
}
The scanner.nextLine() call inside catch is required. When nextInt() fails, the invalid token stays in the scanner's buffer. Without consuming it, the next loop iteration reads the same bad input and fails again in an infinite loop.