How to safely read integers with Scanner in Java without buffer issues
Purpose
This post demonstrates how to safely read integer input in Java using Scanner class.
Environment
- Java 21
- Standard library Scanner class
The Problem
When I run this simple program:
import java.util.Scanner;
public class UnsafeIntInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: "); int age = scanner.nextInt(); // Leaves newline in buffer
System.out.print("Enter name: "); String name = scanner.nextLine(); // Skips immediately!
System.out.println("Age: " + age + ", Name: " + name); }}I get this output:
Enter age: 25Enter name: Age: 25, Name:The name prompt seems to be skipped and the program reads an empty string. This is frustrating when you’re trying to build a simple console application.
What happened?
I was trying to read an integer followed by a string from user input. I used nextInt() for the age and nextLine() for the name. But the nextLine() call didn’t wait for input - it immediately returned an empty string.
Here’s what I think happened:
nextInt()reads only the “25” but leaves the newline character in the input buffernextLine()immediately reads that leftover newline, thinking it’s a complete line- The program continues without waiting for actual name input
I can explain the key parts:
nextInt()only parses the integer token but doesn’t consume the newlinenextLine()reads everything until the next newline character- When there’s already a newline in the buffer,
nextLine()reads it immediately
But when I try to use nextInt() followed by nextLine(), I get this behavior where the second prompt gets skipped.
How to solve it?
I tried to add a dummy nextLine() call after nextInt():
System.out.print("Enter age: ");int age = scanner.nextInt();scanner.nextLine(); // Consume the newline
System.out.print("Enter name: ");String name = scanner.nextLine();
System.out.println("Age: " + age + ", Name: " + name);What changed and why:
- I added a dummy
nextLine()call afternextInt()to consume the leftover newline - This forces the next
nextLine()to wait for actual user input
Now test again:
Enter age: 25Enter name: JohnAge: 25, Name: JohnYou can see that I succeeded to get both inputs correctly.
The Better Solution
The dummy nextLine() approach works, but I think there’s a cleaner solution that’s more robust.
I tried reading the entire line first, then parsing the integer:
import java.util.Scanner;
public class SafeIntInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
try { System.out.print("Enter age: "); String ageStr = scanner.nextLine(); int age = Integer.parseInt(ageStr);
System.out.print("Enter name: "); String name = scanner.nextLine();
System.out.println("Age: " + age + ", Name: " + name); } catch (NumberFormatException e) { System.out.println("Error: Please enter a valid integer for age"); } }}This approach:
- Always reads the entire line using
nextLine() - Uses
Integer.parseInt()to convert the string to integer - Wraps in try-catch to handle
NumberFormatException
Now test again with invalid input:
Enter age: twenty-fiveError: Please enter a valid integer for ageAnd with valid input:
Enter age: 30Enter name: JaneAge: 30, Name: JaneYou can see that I succeeded to handle both valid and invalid input gracefully.
The reason
I think the key reason for the buffer issue is:
nextInt()only reads the integer token and leaves the newline character in the input buffernextLine()reads everything until the next newline character- When there’s already a newline in the buffer,
nextLine()consumes it immediately
The “read line, parse integer” pattern works because:
nextLine()always consumes the entire line including the newlineInteger.parseInt()gives us the integer parsing with built-in error handling- We have complete control over the input processing flow
Summary
In this post, I showed how to safely read integer input in Java. The key point is to always use nextLine() + Integer.parseInt() instead of nextInt() to avoid buffer issues and get better error handling.
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