Sub topic 5
The Leftover Newline Pitfall
This chapter assumes you know basic Java syntax, variables, methods, String, primitive types, and simple exception handling. It also assumes you can compile and run a Java program from the command line.
When a Scanner reads console input, token methods and line methods follow different rules:
- Token methods such as
nextInt(),nextDouble(), andnext()read one token. - The line method
nextLine()reads everything through the end of the current line. - Pressing Enter adds a line terminator after the input.
The common error appears when a program uses a token method and then immediately calls nextLine().
What `nextInt()` leaves behind
Suppose the user types:
42The input contains the characters 4, 2, and a line terminator. nextInt() reads 42, but it does not consume the line terminator. The scanner is now positioned immediately before the newline.
When nextLine() runs, it reads from that position up to the end of the line. Since there are no characters before the newline, it returns an empty string.
The scanner is behaving correctly. It is not skipping the user's title. The call to nextLine() is consuming the remainder of the same line, which is only the leftover newline.
Reproducing the problem
import java.util.Scanner;
public class BrokenInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Count: ");
int count = in.nextInt();
System.out.print("Title: ");
String title = in.nextLine();
System.out.println(count + " x " + title);
}
}If you enter 3, the program prints the result with an empty title. Depending on the terminal, the Title: prompt may appear before you have time to type anything because nextLine() returns immediately.
The standard fix
Call nextLine() once after the token read. This consumes the rest of the current line, including its newline. The next nextLine() then waits for a real line.
import java.util.Scanner;
public class MixedReads {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Count: ");
int count = in.nextInt();
in.nextLine(); // consume the rest of the count line
System.out.print("Title: ");
String title = in.nextLine();
System.out.println(count + " x " + title);
}
}With this program, the following interaction works as expected:
Count: 3
Title: Java Basics
3 x Java BasicsThe extra call is appropriate when the number and the text are entered on separate lines. If the user types 3 Java Basics on one line, the first nextLine() returns " Java Basics" instead. The input format must therefore match the reading strategy.
Avoiding mixed reading styles
For forms with several text fields, a simple approach is to read every field with nextLine() and convert numeric text explicitly.
import java.util.Scanner;
public class LineOrientedInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Count: ");
int count = Integer.parseInt(in.nextLine().trim());
System.out.print("Title: ");
String title = in.nextLine();
System.out.println(count + " x " + title);
}
}This approach avoids the leftover-newline problem because every read consumes a complete line. trim() removes spaces around the number before Integer.parseInt() converts it.
A useful rule is:
- Use token methods when whitespace-separated values are the input format.
- Use
nextLine()consistently when each answer occupies a line. - If you mix them, consume the remaining line after each token read before reading the next complete line.
Exercise
Exercise
Why does nextLine() return an empty string after nextInt(), and what change makes it read the user's next line?
Show answer
nextInt() leaves the line terminator unread. Call nextLine() once to consume the rest of that line, then call nextLine() again to read the next line.