Question

Java Scanner nextLine() After nextInt(): Why Input Is Skipped

javaiojava.util.scanner

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 as 3.
  • 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.

Take Quiz

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.

An alternative is to read every value with nextLine() and convert numeric text yourself:

System.out.println("Enter numerical value:");
int option = Integer.parseInt(input.nextLine());

System.out.println("Enter 1st string:");
String string1 = input.nextLine();

Using nextLine() consistently is often easier for interactive console programs.

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:

  1. nextInt() reads 25 and stores it in age.
  2. Pressing Enter added a newline character after 25.
  3. That newline was not consumed by nextInt().
  4. The program prints Name: .
  5. nextLine() immediately finds the leftover newline.
  6. nextLine() consumes it and returns "".
  7. name becomes an empty string, so the program does not pause for a name.

Corrected version:

System.out.print("Age: ");
int age = input.nextInt();
input.nextLine();

System.out.print("Name: ");
String name = input.nextLine();

Now the first nextLine() clears the pending newline, and the second waits for the user's 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.

Take Quiz

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);
} catch (NumberFormatException exception) {
    System.out.println("Please enter a whole number.");
}

Pattern 3: Use a dedicated input method

In larger console applications, a helper method can repeatedly request a valid integer while keeping all input line-based:

static int readInt(Scanner scanner, String prompt) {
    while (true) {
        System.out.print(prompt);
        try {
            return Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException exception) {
            System.out.println("Enter a valid whole number.");
        }
    }
}

This avoids mixing nextInt() and nextLine() throughout the application.

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:

String fullName = input.nextLine();

Calling extra nextLine() calls everywhere

Adding a clearing nextLine() before every text input can accidentally discard real user input. Add it only after a token-based call when the rest of that line should be ignored.

Not handling invalid numeric input

This can throw InputMismatchException:

int option = input.nextInt();

if the user enters three. For robust interactive programs, read a line and parse it, or check with hasNextInt().

Closing a Scanner that wraps System.in too early

Closing it also closes System.in, so later code cannot read from the console. In small one-method programs this is usually not a problem at program exit, but avoid closing it while other code still needs standard input.

Comparisons

MethodWhat it readsStops atCan include spaces?Leaves newline after Enter?
next()One tokenAny whitespaceNoUsually yes
nextInt()One integer tokenWhitespace after the numberNot applicableYes
nextDouble()One decimal tokenWhitespace after the numberNot applicableYes
nextLine()The rest of the current lineLine breakYesNo; it consumes the line break

next() and nextInt() are token-based: they skip leading whitespace and read one token. nextLine() is line-based: it reads from the current position to the end of the line.

For console forms where each prompt should accept one whole line, nextLine() plus parsing is often the clearest approach.

Take Quiz

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() after nextInt(), nextDouble(), or next() 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 Integer.parseInt() is often easier when your program also reads text lines and needs validation.

Can nextLine() read text with spaces?

Yes. nextLine() reads all text until Enter, including spaces. This makes it suitable for full names, addresses, and messages.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more