How to validate user input with Scanner in Java: Handle non-numeric input
Purpose
This post demonstrates how to handle Scanner input validation when users enter non-numeric input in Java.
Environment
- Java 21
- Standard Java Scanner class
- Console input handling
The Problem
When I try to get numeric input from users, I got this error:
Scanner scanner = new Scanner(System.in);System.out.print("Enter age: ");int age = scanner.nextInt(); // Throws InputMismatchException for "twenty"The error looks like this:
Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2242) at Main.main(Main.java:10)What happened?
I was trying to get user input for an age. The user entered “twenty” instead of a number, and the program crashed.
Here’s my setup:
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: "); int age = scanner.nextInt();
System.out.println("Your age is: " + age); scanner.close(); }}I can explain the key parts:
Scanner scanner = new Scanner(System.in): Creates a scanner for console inputscanner.nextInt(): Expects to read an integer from inputscanner.close(): Closes the scanner when done
But when I run this and enter “twenty”, I got this error:
Enter age: twentyException in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2242) at Main.main(Main.java:10)How to solve it?
I tried to catch the exception:
Scanner scanner = new Scanner(System.in);System.out.print("Enter age: ");
try { int age = scanner.nextInt(); System.out.println("Your age is: " + age);} catch (InputMismatchException e) { System.out.println("Please enter a valid number");}scanner.close();Explain why you tried this - brief. This prevents the program from crashing, but it doesn’t handle the case where the user enters invalid input multiple times.
Then I tried using hasNextInt() to validate input first:
Scanner scanner = new Scanner(System.in);System.out.print("Enter age: ");
while (!scanner.hasNextInt()) { System.out.println("Invalid input. Please enter a number:"); scanner.next(); // Clear invalid input}
int age = scanner.nextInt();System.out.println("Your age is: " + age);scanner.close();What changed and why. Now I check if the next input is an integer before trying to read it. If not, I clear the invalid input with next() and ask again.
Now test again:
Scanner scanner = new Scanner(System.in);System.out.print("Enter age: ");
while (!scanner.hasNextInt()) { System.out.println("Invalid input. Please enter a number:"); scanner.nextLine(); // Clear the entire invalid line}
int age = scanner.nextInt();scanner.nextLine(); // Clear the newlineSystem.out.println("Your age is: " + age);scanner.close();You can see that I succeeded to handle multiple invalid inputs gracefully and get a valid number.
The complete solution
Here’s a complete working example with a reusable method:
import java.util.Scanner;
public class InputValidator {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
int age = getValidIntInput(scanner, "Enter age: "); System.out.println("Your age is: " + age);
scanner.close(); }
private static int getValidIntInput(Scanner scanner, String prompt) { System.out.print(prompt);
while (!scanner.hasNextInt()) { System.out.println("Invalid input. Please enter a number:"); scanner.nextLine(); // Clear invalid input }
int result = scanner.nextInt(); scanner.nextLine(); // Clear the newline return result; }}You can see that I created a reusable method that handles all the validation logic.
The reason
I think the key reason for the error is:
- Scanner.nextInt() expects exactly a valid integer format
- When invalid input is found, it doesn’t consume anything from the input buffer
- This leaves the invalid input in the buffer, causing the same exception on the next call
- hasNextInt() checks if the next token can be read as an integer without consuming it
- nextLine() consumes the entire line including the invalid input
More advanced example
Here’s a more complete example with multiple input types:
import java.util.Scanner;
public class MultiInputValidator {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
int age = getValidIntInput(scanner, "Enter age: "); String name = getValidStringInput(scanner, "Enter name: "); double salary = getValidDoubleInput(scanner, "Enter salary: ");
System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary);
scanner.close(); }
private static int getValidIntInput(Scanner scanner, String prompt) { System.out.print(prompt);
while (!scanner.hasNextInt()) { System.out.println("Invalid input. Please enter a whole number:"); scanner.nextLine(); }
int result = scanner.nextInt(); scanner.nextLine(); return result; }
private static String getValidStringInput(Scanner scanner, String prompt) { System.out.print(prompt); return scanner.nextLine().trim(); }
private static double getValidDoubleInput(Scanner scanner, String prompt) { System.out.print(prompt);
while (!scanner.hasNextDouble()) { System.out.println("Invalid input. Please enter a valid number:"); scanner.nextLine(); }
double result = scanner.nextDouble(); scanner.nextLine(); return result; }}Summary
In this post, I demonstrated how to handle Scanner input validation in Java. The key point is to use hasNextInt() to validate input before calling nextInt(), and clear invalid input with nextLine() to prevent infinite loops and crashes.
Final Words + More Resources
My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!
Comments