Sub topic 7
Reading Until the Input Ends
Prerequisites and the meaning of end of input
This chapter assumes that you know basic Java syntax, can compile and run a program from the command line, and understand variables, loops, String, primitive types, and basic exceptions.
A console program does not always know how many values a user will provide. Instead, it can read values until the input ends. The end of input is called EOF, or end of file. For interactive terminal input, you usually signal EOF with Ctrl+D on Linux and macOS, or Ctrl+Z followed by Enter on Windows. A redirected file reaches EOF automatically when the last byte has been read.
System.in is Java's standard input stream. A Scanner can test whether more input is available before reading it.
Test before you read
Methods such as nextInt() and nextLine() expect input to be available. If the input has already ended, calling them can throw NoSuchElementException. The matching hasNext... methods let the program check first.
| Method | Checks for | Reads the value? |
|---|---|---|
| `hasNext()` | Another token | No |
| `hasNextLine()` | Another line | No |
| `hasNextInt()` | An integer token | No |
| `nextInt()` | The next integer | Yes |
The check does not consume input. After hasNextInt() returns true, nextInt() reads the same integer.
Read integers until EOF
This program adds every integer supplied on standard input. It keeps reading while the next token is an integer.
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);
}
}You can run it and type several integers separated by spaces or lines:
4 7
-2After sending EOF, the program prints:
Sum: 9The loop also stops if the next token is not an integer. For example, input such as 4 seven 2 produces a sum of 4; it does not skip seven and continue to 2.
That behavior may be correct when invalid input should end the data stream. If invalid tokens should be ignored, test with hasNext() and consume the bad token with next().
import java.util.Scanner;
public class SumValidIntegers {
public static void main(String[] args) {
int sum = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNext()) {
if (in.hasNextInt()) {
sum += in.nextInt();
} else {
System.out.println("Ignoring: " + in.next());
}
}
}
System.out.println("Sum: " + sum);
}
}The hasNext() condition prevents the final next() call from running after EOF. Without it, the program could throw NoSuchElementException.
Read lines until EOF
For line-oriented input, use hasNextLine() with nextLine():
import java.util.Scanner;
public class LineCounter {
public static void main(String[] args) {
int lines = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!line.isBlank()) {
lines++;
}
}
}
System.out.println("Nonblank lines: " + lines);
}
}This pattern works well for files redirected into a program:
java LineCounter < notes.txtClosing and choosing a loop
Try-with-resources closes the Scanner automatically. Closing a scanner created from System.in also closes System.in. That is useful when the program is finished reading, but it can cause problems if another part of the program still needs standard input.
Use hasNextInt() for a stream of integers, hasNextLine() for complete lines, and hasNext() when processing arbitrary tokens.
Exercise
Which loop condition should you use to read complete text lines until EOF, and which exception can occur if you call nextLine() after EOF without checking?
Show answer
Use hasNextLine(). Calling nextLine() after EOF can throw NoSuchElementException.