Sub topic 7
Reading Until the Input Ends
Many programs do not know in advance how much input they will get. A word counter, a log filter, and a program that sums numbers piped from another command all read until nothing is left. This chapter covers how Scanner signals the end of input, how to write loops that stop cleanly, and what goes wrong when they don't.
This chapter assumes you can create a Scanner on System.in, and that you know the difference between token reads (next, nextInt) and line reads (nextLine). It also assumes you know the leftover-newline pitfall and the hasNextInt validation pattern from the earlier chapters.
What "end of input" means
Standard input is a stream of characters. It ends when whatever feeds it has nothing more to send. This happens in three common cases:
- You redirect a file into the program:
java SumAll < numbers.txt. The input ends when the file does. - Another program pipes output into yours:
cat numbers.txt | java SumAll. The input ends when that program exits or closes its output. - You type at the keyboard and signal the end yourself. On Linux and macOS press Ctrl+D on an empty line. On Windows press Ctrl+Z, then Enter.
Pressing Enter does not end the input. It only adds a line terminator to the stream. Many beginners wait for a loop to stop after pressing Enter on an empty line, and it never does.
The has-methods and the next-methods
A Scanner offers a hasNext... method for each next... method. The has method looks ahead and returns a boolean without consuming anything. The next method consumes the input, and it throws an exception if nothing suitable is there.
| Check | Read | Thrown by the read when the check would be false |
|---|---|---|
| `hasNext()` | `next()` | `NoSuchElementException` |
| `hasNextLine()` | `nextLine()` | `NoSuchElementException` ("No line found") |
| `hasNextInt()` | `nextInt()` | `InputMismatchException` if a token exists but is not an int, `NoSuchElementException` if there are no tokens left |
| `hasNextDouble()` | `nextDouble()` | same as `nextInt` |
InputMismatchException is a subclass of NoSuchElementException. A catch (NoSuchElementException e) therefore also catches bad-format errors, which can hide the real cause. Prefer checking with the has methods before reading, so you don't depend on exceptions for normal control flow.
A has method that cannot answer yet will block. In an interactive session, hasNext() waits until you type something or signal the end of input. It returns false only after the end has been reached.
Reading lines until the end
For line-oriented input, loop on hasNextLine:
import java.util.Scanner;
public class LineStats {
public static void main(String[] args) {
int lines = 0;
int words = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
lines++;
if (!line.isBlank()) {
words += line.trim().split("\\s+").length;
}
}
}
System.out.println("Lines: " + lines);
System.out.println("Words: " + words);
}
}Run it with java LineStats < notes.txt. Each pass of the loop reads exactly one line, and the loop ends when hasNextLine returns false.
The isBlank check matters because "".split("\\s+") returns an array with one empty string. Without the check, every empty line would count as one word.
Reading tokens until the end
For numbers or words separated by any whitespace, loop on hasNextInt or hasNext. This is the pattern from SumAll:
import java.util.Scanner;
public class SumAll {
public static void main(String[] args) {
int sum = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextInt()) {
sum += in.nextInt();
}
}
System.out.println("Sum: " + sum);
}
}This loop has a subtle property. hasNextInt() returns false in two different situations: the input has ended, or the next token is not an integer. The loop cannot tell which one happened. Given the input 10 20 abc 30, it prints Sum: 30 and silently ignores 30 after the bad token, because the loop stops at abc.
Sometimes that is what you want. When it is not, separate the two cases with hasNext:
import java.util.Scanner;
public class SumSkipping {
public static void main(String[] args) {
int sum = 0;
int skipped = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNext()) {
if (in.hasNextInt()) {
sum += in.nextInt();
} else {
in.next(); // consume the bad token so the loop makes progress
skipped++;
}
}
}
System.out.println("Sum: " + sum + ", skipped: " + skipped);
}
}With the input 10 20 abc 30, this prints Sum: 60, skipped: 1.
The trailing-newline edge case
Mixing a token loop with a line read produces a confusing result at the end. Suppose the input is 1 2 3 followed by a newline:
import java.util.Scanner;
public class TrailingNewline {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
in.nextInt();
}
System.out.println(in.hasNextLine());
System.out.println("[" + in.nextLine() + "]");
}
}This prints true and then []. After nextInt reads 3, the terminating newline is still unread. hasNextLine sees one more (empty) line, and nextLine returns an empty string. This is the same mechanism as the leftover-newline pitfall, and it shows up here too.
Line counting follows a related rule. The line terminator ends a line. It does not start a new one. Here is how hasNextLine loops count different inputs:
| Input characters | Lines seen by a `hasNextLine` loop |
|---|---|
| `a` (no terminator) | 1 line: `a` |
| `a\n` | 1 line: `a` |
| `a\n\n` | 2 lines: `a` and an empty line |
| (nothing) | 0 lines |
NoSuchElementException
If you call a next method without checking, and the input has ended, you get an exception. The classic case is a program that asks a fixed number of questions:
import java.util.Scanner;
public class Unchecked {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine(); // throws if stdin is empty
System.out.println("Hello, " + name);
}
}Run java Unchecked < /dev/null (or java Unchecked < NUL on Windows) and the program fails with java.util.NoSuchElementException: No line found. The same happens when a user presses Ctrl+D at the prompt.
You have two options. If the missing input is a normal possibility, check with hasNextLine first and handle false. If the program cannot continue without the input, let the exception be informative. The readInt helper from the validation chapter does this by throwing an IllegalStateException with the message "Input ended". Either way, a clear failure is better than a stack trace from deep inside Scanner.
Stopping early with a sentinel
You don't have to read to the true end. An interactive program often reads until the user types a special word, called a sentinel value. Combine the sentinel with the end-of-input check, so that Ctrl+D also works:
import java.util.Scanner;
public class Echo {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.print("> ");
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("quit")) {
break;
}
System.out.println("You said: " + line);
System.out.print("> ");
}
}
System.out.println("Bye");
}
}The loop condition handles the end of input, and the break handles the sentinel. Putting the prompt before the loop and again at the end of each pass means the user always sees a prompt before the program blocks in hasNextLine.
The same loop with BufferedReader
BufferedReader signals the end differently. It has no has method. Its readLine returns null when the input is over, so the usual idiom assigns and tests in one expression:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountLines {
public static void main(String[] args) throws IOException {
int lines = 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = reader.readLine()) != null) {
lines++;
}
}
System.out.println("Lines: " + lines);
}
}The two approaches treat errors differently. BufferedReader makes you handle IOException, and it never throws NoSuchElementException. Scanner hides read failures behind its end-of-input signal, but its has methods let you check the type of the next token.
Closing and the end of input
The try-with-resources blocks above close the Scanner, which also closes System.in. That is fine at the end of the program. Do not do it in a helper method that a caller might call twice. After System.in is closed, a new Scanner on it sees no input, and hasNextLine returns false immediately. This looks exactly like a normal end of input, which makes the bug hard to spot.
Common mistakes
- Looping on
hasNextIntand assuming the input was fully read. The loop also stops at the first non-integer token. CheckhasNextafterward if leftover input would be an error. - Calling
nextLineafter a token loop without expecting an empty string. The newline after the last token is still unread. - Skipping bad tokens without consuming them. The loop never advances.
- Waiting for Enter on an empty line to end input. Only Ctrl+D or Ctrl+Z, or the end of a redirected file, ends the stream.
- Reading with
next...methods when the input might be empty. Always check first, or catchNoSuchElementExceptiondeliberately.
Exercise
A program reads numbers with while (in.hasNextInt()) { sum += in.nextInt(); }. The input is 4 5 six 7. What is the sum, and how would you change the loop so that it reports the bad token and still adds up 7?
Show answer
The sum is 9, because the loop stops at six, and 7 is never read. To continue past the bad token, loop on in.hasNext(). Inside, if in.hasNextInt() is true, add in.nextInt(). Otherwise call in.next() to consume the bad token, and print it. With this change the sum is 16.
Exercise
You run java LineStats and type three lines, pressing Enter after each. The program prints nothing and keeps waiting. Why, and what do you do on Linux or Windows to make it finish?
Show answer
Pressing Enter only ends a line, and the input stream is still open, so hasNextLine blocks waiting for more. Signal the end of input: press Ctrl+D on an empty line on Linux or macOS, or Ctrl+Z followed by Enter on Windows.
Exercise
Write a loop that reads lines until the input ends or the user types done, then prints how many lines were read before that point.
Show answer
Use a counter and a hasNextLine loop:
int count = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("done")) break;
count++;
}
System.out.println(count);
The done line itself is not counted, because the break happens before the increment.