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:
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:
- 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:
- Using
nextLine()exclusively: Convert the string result fromnextLine()to the appropriate data type manually.
Summary Table:
| Method | Usage | Side Effect | Resolution |
nextInt(), etc. | Reads data until space ( ) or newline (\n) | Leaves newline character in the stream | Use extra nextLine() to consume newline |
nextLine() | Reads the rest of the current line | None inherently | -- |
Additional Considerations
- Mixing
next()andnextLine(): Be aware when mixing different scanning methods, and consciously manage the newline characters. ScannerBuffering:Scannerbuffers 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.

