Programming
Java
Scanner Class
Debugging
Code Issues

Scanner is skipping nextLine() after using next() or nextFoo()?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Using a Scanner in Java is commonplace for reading input from the command line, files, or even network sources. However, a frequent issue that programmers encounter when using Scanner is that the method nextLine() seems to be skipped or overlooked immediately following a next(), nextInt(), nextDouble(), etc. In this article, we'll explore why this behavior occurs and how to handle it efficiently.

Why Does nextLine() Get Skipped?

The Scanner class in Java uses different methods to read various types of input from the source. These methods include next(), which reads a token separated by spaces; nextInt(), nextDouble(), etc., which read numerical values; and nextLine(), which reads the entire line up to the end of line character \n.

When Scanner reads input using the methods next(), nextInt(), etc., it consumes only the data but leaves behind the newline character (if the input ends with a new line). Consequently, when a subsequent nextLine() is called, it reads the leftover newline character from the previous input, interprets it as the end of an (empty) line, and hence, returns an empty string. This gives the impression that nextLine() is being skipped.

Example of the Issue

Consider the following example:

java
1import java.util.Scanner;
2
3public class Main {
4    public static void main(String[] args) {
5        Scanner scanner = new Scanner(System.in);
6
7        System.out.print("Enter an integer: ");
8        int number = scanner.nextInt(); // Input is "10\n"
9
10        System.out.print("Enter a line of text: ");
11        String line = scanner.nextLine(); // Expected to wait for text input
12
13        System.out.println("Number: " + number);
14        System.out.println("Text: " + line);
15    }
16}
17

If you input 10 followed by an Enter for nextInt(), you would expect the nextLine() to wait for your text input. However, line ends up being an empty string.

Efficient Handling of nextLine() Skipping

There are several ways to handle this scenario effectively:

  1. Consume the lingering newline character: Immediately after reading a numeric or single-word value, add an extra nextLine() call to consume the excessive newline, like so:
java
    int number = scanner.nextInt(); // Input is "10\n"
    scanner.nextLine();  // Consume the newline
    String line = scanner.nextLine(); // Now this works as intended
  1. Using nextLine() exclusively: Convert the string result from nextLine() to the appropriate data type manually.
java
    String numberStr = scanner.nextLine(); // Read the line and process it
    int number = Integer.parseInt(numberStr.trim());
    String line = scanner.nextLine(); // No skipping issue

Summary Table:

MethodUsageSide EffectResolution
nextInt(), etc.Reads data until space ( ) or newline (\n)Leaves newline character in the streamUse extra nextLine() to consume newline
nextLine()Reads the rest of the current lineNone inherently--

Additional Considerations

  • Mixing next() and nextLine(): Be aware when mixing different scanning methods, and consciously manage the newline characters.
  • Scanner Buffering: Scanner buffers input, which can affect how it reads subsequent data. Understanding this behavior helps prevent errors in data handling.
  • Performance Impact: Improper use of scanner methods, especially in loops, may lead to performance issues or bugs due to unexpected behavior like this.

By understanding these subtleties of the Scanner class, Java programmers can avoid common pitfalls and ensure data is read correctly in different scenarios.


Course illustration
Course illustration

All Rights Reserved.