Question
I am using Java's Scanner methods nextInt() and nextLine() to read input:
System.out.println("Enter numerical value");
int option = input.nextInt();
System.out.println("Enter 1st string");
String string1 = input.nextLine();
System.out.println("Enter 2nd string");
String string2 = input.nextLine();
After I enter a number such as 3, the first call to input.nextLine() appears to be skipped. The program immediately prints Enter 2nd string and waits for input there.
Why does this happen after using nextInt(), and how can I read both string lines correctly?
Short Answer
You will learn how Java Scanner reads tokens and complete lines, why nextInt() leaves a newline behind, and two reliable ways to combine numeric and text input.
Concept
Scanner has methods that read input in different ways:
nextInt()reads only an integer token, such as3.next()reads one whitespace-separated token.nextLine()reads every remaining character on the current line, up to the line break.
When you type this and press Enter:
3↵
nextInt() consumes the 3, but it does not consume the line break created by pressing Enter. That line break remains waiting in the input stream.
The next nextLine() sees that it is already at the end of the current line. Therefore, it consumes the leftover line break and returns an empty string ("") immediately. It is not truly skipped; it successfully reads an empty remainder of the line.
This matters whenever a program mixes token-reading methods (nextInt, nextDouble, next) with line-reading (nextLine).
Mental Model
Imagine user input as text written on a roll of paper:
3\nfirst message\nsecond message\n
nextInt() uses scissors to cut out only the 3. The newline (\n) is still the next character on the paper.
Then nextLine() is asked to read until the next newline. But the very next character is already a newline, so it reads zero visible characters and returns an empty string.
Call nextLine() once to clear that leftover newline before asking for the actual text line.
Syntax and Examples
Use an extra nextLine() after nextInt() to consume the rest of the number's line.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value:");
int option = input.nextInt();
input.nextLine(); // Consume the leftover newline.
System.out.println("Enter 1st string:");
String string1 = input.nextLine();
System.out.println("Enter 2nd string:");
String string2 = input.nextLine();
System.out.println("Option: " + option);
System.out.println("First: " + string1);
System.out.println("Second: " + string2);
}
}
The extra input.nextLine() is not intended to collect the first string. Its job is to consume the remainder of the line containing the number.
Step by Step Execution
Consider this program:
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
System.out.print("Name: ");
String name = input.nextLine();
Suppose the user types:
25↵
Execution proceeds as follows:
nextInt()reads25and stores it inage.- Pressing Enter added a newline character after
25. - That newline was not consumed by
nextInt(). - The program prints
Name:. nextLine()immediately finds the leftover newline.nextLine()consumes it and returns"".namebecomes an empty string, so the program does not pause for a name.
Real World Use Cases
Mixing numeric and text input is common in command-line programs:
- Registration form: read an age, then a full name and address.
- Menu program: read a numeric menu choice, then request a comment or search phrase.
- Inventory tool: read quantity and price, then read a product description.
- School application: read an ID number, then a student name and course title.
- Simple games: read a numeric difficulty level, then a player name.
In each case, account for the newline left by token-based methods before reading a full text line.
Real Codebase Usage
For small console programs, developers usually choose one of these patterns.
Pattern 1: Consume the newline after token input
int quantity = scanner.nextInt();
scanner.nextLine();
String description = scanner.nextLine();
Use this when nextInt() is convenient and you have validated that the user entered an integer.
Pattern 2: Read complete lines and parse them
String quantityText = scanner.nextLine();
int quantity = Integer.parseInt(quantityText.trim());
String description = scanner.nextLine();
This is often preferred for interactive input because each prompt corresponds to exactly one input line. It also makes validation easier:
System.out.print("Enter quantity: ");
String text = scanner.nextLine();
try {
int quantity = Integer.parseInt(text.trim());
System.out.println("Quantity: " + quantity);
} (NumberFormatException exception) {
System.out.println();
}
Common Mistakes
Expecting nextInt() to consume Enter
Broken assumption:
int option = input.nextInt();
String title = input.nextLine();
title becomes "" if the user pressed Enter after the number.
Fix it by consuming the newline:
int option = input.nextInt();
input.nextLine();
String title = input.nextLine();
Using next() when spaces should be allowed
String fullName = input.next();
If the user enters Ada Lovelace, this reads only Ada.
Use nextLine() for sentences, names with spaces, addresses, and descriptions:
Comparisons
| Method | What it reads | Stops at | Can include spaces? | Leaves newline after Enter? |
|---|---|---|---|---|
next() | One token | Any whitespace | No | Usually yes |
nextInt() | One integer token | Whitespace after the number | Not applicable | Yes |
nextDouble() | One decimal token | Whitespace after the number | Not applicable | Yes |
nextLine() | The rest of the current line | Line break | Yes |
Cheat Sheet
// Token-based numeric input followed by line input
int number = scanner.nextInt();
scanner.nextLine(); // Clear the pending newline
String text = scanner.nextLine();
// Line-based input for everything
int number = Integer.parseInt(scanner.nextLine().trim());
String text = scanner.nextLine();
nextInt()reads the number, not the Enter newline.next()reads one word/token, not a complete sentence.nextLine()can return""when it starts at a line break.- Use one clearing
nextLine()afternextInt(),nextDouble(), ornext()when reading the next full line. - Use
.trim()before parsing if surrounding spaces should be accepted. - Validate user input before assuming it is a number.
FAQ
Why does nextLine() skip after nextInt() in Java?
nextInt() leaves the newline from pressing Enter in the input stream. The following nextLine() consumes that newline and returns an empty string.
How do I fix Scanner nextLine() being skipped?
Call scanner.nextLine() once immediately after scanner.nextInt() to consume the leftover newline, then call nextLine() again to read the actual text.
Does the same problem happen with nextDouble() and next()?
Yes. These methods also read tokens rather than the complete line, so a later nextLine() may read the remaining line break.
Why is the first string empty instead of missing?
It is not missing. The first nextLine() successfully reads the empty remainder of the line after the number.
Should I use nextInt() or nextLine() for numbers?
For simple programs, either works. Reading with nextLine() and converting with is often easier when your program also reads text lines and needs validation.
Mini Project
Description
Build a small console-based profile collector. It asks for a numeric age, then collects a full name and a short biography. The project demonstrates how to safely combine numeric and multi-word text input.
Goal
Collect and display a user's age, full name, and biography without accidentally reading an empty text line.
Requirements
Use one Scanner connected to System.in. Ask the user for an age as a whole number. Read a full name that may contain spaces. Read a biography that may contain spaces. Display all collected values in a clear summary.
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.