How to Check If Scanner Input Is Integer in Java
Learn how to check if scanner input is integer java using hasNextInt, parseInt with try/catch, or regex validation. Practical code and best practices for robust input handling.

In Java, you can determine if scanner input is an integer by using hasNextInt() before nextInt(), or by reading a token and parsing it with Integer.parseInt() inside a try/catch block. This guards against non-integer input and prevents runtime crashes, providing clear handling paths for valid and invalid data.
How to check if scanner input is integer java
When you read user input with a java.util.Scanner, the simplest way to verify an integer token is to use hasNextInt() before consuming the value with nextInt(). This two-step check avoids InputMismatchException and lets you provide friendly feedback for non-integer input. The keyword here is defensive input handling: validate before you parse. Below are practical patterns you can adapt in real-world apps.
import java.util.Scanner;
public class HasNextIntDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
if (sc.hasNextInt()) {
int value = sc.nextInt();
System.out.println("You entered: " + value);
} else {
System.out.println("Invalid input: not an integer.");
// Optional: flush the invalid token
sc.next();
}
sc.close();
}
}Why this works: hasNextInt() peeks at the next token without consuming it, so you can decide the next step safely. This approach is great for prompt-driven console apps where you want immediate user feedback.
wordCountSectionBreaksNote": null
sectionNote": null
Steps
Estimated time: 15-30 minutes
- 1
Create a Java file
Open your editor and create a new file named IntInputDemo.java. This file will host a small program that reads input from System.in using Scanner.
Tip: Keep a clean package structure to ease compilation later. - 2
Write guarded input logic
Implement hasNextInt() check before nextInt(), so you can handle non-integer input gracefully.
Tip: Comment the decision points to aid future maintenance. - 3
Compile the program
Run javac IntInputDemo.java to compile the class. Fix any syntax errors before proceeding.
Tip: Ensure your CLASSPATH is set correctly if you’ve organized packages. - 4
Run and test
Execute java IntInputDemo and provide both valid and invalid inputs to verify behavior.
Tip: Try edge cases like large numbers and whitespace-only input. - 5
Extend with parsing
Add an alternative path that uses Integer.parseInt() inside a try/catch for flexibility.
Tip: Remember, parseInt throws NumberFormatException on invalid data. - 6
Review edge cases
Consider locale, newline handling, and long-term input robustness for production use.
Tip: Document assumptions about input format and error handling.
Prerequisites
Required
- Required
- A Java IDE or editor (e.g., IntelliJ IDEA, VS Code)Required
- Basic knowledge of Java syntax and Scanner usageRequired
- Command-line terminal familiarityRequired
Optional
- Optional: Maven or Gradle for project setupOptional
Commands
| Action | Command |
|---|---|
| Compile Java fileEnsure the file's public class matches the filename. | — |
| Run programProvide input via keyboard or redirection. | — |
| Test valid input with pipePipes feed a valid integer. | — |
| Test invalid input with pipeObserve non-integer handling output. | — |
Common Questions
What is the difference between hasNextInt() and Integer.parseInt()?
hasNextInt() checks the next token without consuming it, enabling a safe pre-check. parseInt() converts a string and can throw NumberFormatException if the token isn't a valid integer. Choose hasNextInt for guard-read flows, or parseInt with try/catch when you already have a string value.
Use hasNextInt to peek safely, or parseInt with error handling if you already read a string.
Can I rely on nextInt() for all integer input?
nextInt() reads the next token as an int and throws InputMismatchException on invalid input. It is convenient, but you should guard it with hasNextInt() or catch the exception to provide friendly feedback.
nextInt is handy but you should guard it or catch exceptions for robust apps.
How do I handle invalid input gracefully?
Check input validity before parsing (hasNextInt or regex), inform the user, and clear the invalid token if needed. Consider looping until valid input is received in interactive programs.
Check validity first, tell the user what happened, and retry if appropriate.
Does locale affect integer parsing with Scanner?
Scanner tokenization is influenced by locale settings for numbers with decimal separators. For integer parsing, ensure tokens are digits possibly with a leading minus sign, or explicitly set a consistent Locale when using parsing methods.
Locale can affect number formats; be explicit if you rely on parsing.
Is this approach portable across Java versions?
Yes. The basic Scanner.hasNextInt, nextInt, and Integer.parseInt approaches work across standard Java SE versions. Avoid deprecated APIs and follow current JDK recommendations for input handling.
These input methods work across common Java versions.
Key Takeaways
- Use hasNextInt() to validate before nextInt().
- Catch NumberFormatException when using parseInt().
- Regex validation can pre-filter non-numeric tokens.
- Be mindful of input edge cases and locale effects.
- Test with both valid and invalid inputs to ensure robustness.