Sub topic 5
The leftover newline pitfall
This chapter assumes you can create a Scanner on System.in and know the difference between nextInt() and nextLine(). It also assumes you can run a Java file from the command line. Here you will see why mixing the two calls gives surprising results. You will also see three ways to fix it and a few edge cases the usual one-line fix misses.
The symptom
The program below asks for a count and then a title. It looks correct.
import java.util.Scanner;
public class Broken {
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 + "]");
}
}Run it with java Broken.java, type 3, and press Enter. The program prints the Title: prompt and then immediately finishes without waiting for you:
Count: 3
Title: 3 x []The title is an empty string, and you never got to type one. Nothing threw an exception, which is why this bug is easy to miss.
Why it happens
When you type 3 and press Enter, the terminal sends two characters to the program: 3 and a line terminator (\n on Linux and macOS, \r\n on Windows). Both end up in the input buffer, which is the text the Scanner has received but not yet consumed.
The two methods consume different amounts of that text:
nextInt()is a token method. It skips any delimiters (whitespace) in front of it, reads the characters of one integer, and stops right after the last digit. It does not consume what follows.nextLine()is a line method. It returns everything from the current position up to the next line terminator, and it consumes the terminator but does not include it in the result.
After nextInt() reads 3, the position sits just before the line terminator. The next nextLine() call sees a line that is already finished, returns the empty string, and consumes the terminator. The title you wanted is still waiting behind it.
You can see the same thing in a trace. The | marks the Scanner position.
| Step | Buffer contents | Call | Result | Column |
|---|---|---|---|---|
| 0 | `\ | 3\n` | (start) | |
| 1 | `3\ | \n` | `nextInt()` | `3` |
| 2 | `3\n\ | ` | `nextLine()` | `""` |
The pitfall is not limited to nextInt(). Every token method behaves this way: next(), nextDouble(), nextLong() and nextBoolean(). The rule is that after any token read, the rest of that line, including its terminator, is still unread.
Fix 1: discard the rest of the line
The smallest fix is one extra nextLine() call after the token read. It consumes the leftover terminator and throws away anything else on that 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(); // discard the rest of the line, including the newline
System.out.print("Title: ");
String title = in.nextLine();
System.out.println(count + " x " + title);
}
}Discarding the whole rest of the line, and not just the newline, is deliberate. If the user typed 3 with a trailing space, or 3 apples, the leftover is more than a bare terminator. One nextLine() call removes all of it.
This fix has a cost. You must remember it at every place where a token read is followed by a line read. In a longer program, that is easy to forget.
Fix 2: read lines, then parse
The second approach avoids the problem by never using token methods in a program that also reads lines. Every read is nextLine(), and you convert the text yourself.
import java.util.Scanner;
public class LineOnly {
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);
}
}Because every call consumes exactly one line, the position is always at the start of a line when a read begins. There is nothing to forget.
trim() removes surrounding spaces, which Integer.parseInt would otherwise reject. A bad number throws NumberFormatException, which is a different exception from the InputMismatchException that nextInt() throws. Handle whichever one your approach produces. Validation is covered in its own chapter.
You can put this in a helper so the rest of the program stays clean:
import java.util.Scanner;
public class Helpers {
static int readIntLine(Scanner in, String prompt) {
System.out.print(prompt);
return Integer.parseInt(in.nextLine().trim());
}
static String readLine(Scanner in, String prompt) {
System.out.print(prompt);
return in.nextLine();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = readIntLine(in, "Count: ");
String title = readLine(in, "Title: ");
System.out.println(count + " x " + title);
}
}The trade-off is that this approach reads one value per line. If you want the user to type 3 4 on one line and get two numbers, you have to split the line yourself.
Fix 3: tokens only
If the program never needs a whole line with spaces in it, use token methods everywhere. The consistent use of one style avoids the mismatch. This is a good choice for programs that read numbers or single words, such as the sum loop shown in the Scanner overview.
A title with spaces does not fit this style, because next() returns only up to the next whitespace. Choose based on the data you expect.
| Approach | Best when | Watch out for |
|---|---|---|
| Extra `nextLine()` after each token read | A few mixed reads in a small program | Forgetting the call at one spot |
| Lines only, then parse | Prompts that each take one line | Parse exceptions, one value per line |
| Tokens only | Numbers and single words, such as data piped in | Text containing spaces |
Edge cases
Reading a line first is safe
The order matters. A line read followed by a token read has no problem:
String name = in.nextLine();
int age = in.nextInt();nextLine() consumes its terminator, so nextInt() starts at a fresh position. This is the order the Greeter program from the overview uses. The trouble starts only when a token read comes first and a line read follows.
A token read leaves a "line" behind
After the last token in the input, the leftover terminator still counts as a line. Suppose the input is 5\n:
Scanner in = new Scanner("5\n");
in.nextInt();
System.out.println(in.hasNextLine()); // true
System.out.println("[" + in.nextLine() + "]"); // []A loop that reads tokens and then checks hasNextLine() will therefore see one extra, empty line. If you process lines with hasNextLine(), do not mix in token reads on the same Scanner.
The input ends right after the token
If the input is 5 with no terminator at all, the extra nextLine() from Fix 1 throws NoSuchElementException with the message No line found. This happens with piped input that has no trailing newline. In an interactive terminal it cannot happen, because pressing Enter always sends a terminator. You can test it:
import java.util.Scanner;
public class NoNewline {
public static void main(String[] args) {
Scanner in = new Scanner("5");
in.nextInt();
try {
in.nextLine();
} catch (java.util.NoSuchElementException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}A defensive version of Fix 1 checks first: if (in.hasNextLine()) in.nextLine();.
Windows line endings
On Windows, the terminator is \r\n. Scanner recognizes \r\n, \n, \r and a few other separators as line boundaries, and nextLine() consumes the whole pair. You do not need extra code for it. You may still see stray \r characters if you read with BufferedReader on a file whose line endings differ from what you expect, but that is a separate problem.
A failed token read does not advance
If nextInt() throws InputMismatchException because the next token is abc, the Scanner does not consume abc. Retrying nextInt() in a loop without removing the bad token loops forever. Call next() or nextLine() in the catch block to discard it.
A debugging checklist
When a prompt seems to be skipped, check these in order:
- Find the read that comes just before the skipped prompt. Is it a token read (
next,nextInt,nextDouble,nextBoolean)? - Is the skipped read a
nextLine()? If so, it consumed the rest of the earlier line and returned a blank or short string. - Print the value you got with delimiters around it, such as
"[" + title + "]". An empty pair of brackets points to the leftover terminator. - Add
in.nextLine()after the token read, or switch the program to lines only. - If the failure appears only with piped input, test the no-trailing-newline case.
Exercise
A program runs int a = in.nextInt(); String s = in.nextLine(); and the user types 7 apples and presses Enter. What are the values of a and s?
Show answer
a is 7 and s is " apples" (with a leading space). nextInt() stops right after the 7, so nextLine() returns the rest of the same line, which begins with the space, and consumes the line terminator. The program does not wait for more input.
Exercise
You change the program to in.nextInt(); in.nextLine(); to fix the skipped prompt. It works at the keyboard but fails with NoSuchElementException: No line found when run as printf '5' | java Fixed.java. Why, and how do you make the fix safe?
Show answer
The piped input is 5 with no line terminator, so after nextInt() there is no line left for nextLine() to return. In a terminal, pressing Enter always adds a terminator, so the error does not appear there. Guard the call with if (in.hasNextLine()) in.nextLine();, or read every value with nextLine() and parse it with Integer.parseInt.
Exercise
Why does reading a line first and then a token (nextLine() then nextInt()) not cause the leftover newline problem?
Show answer
nextLine() consumes the line terminator along with the text, so the Scanner position is at the start of the next line when nextInt() runs. The token read then skips any leading whitespace and finds the number. The pitfall needs a token read first, because token methods leave the terminator unread.