Scanner and standard input
Scanner turns text into values: it splits the input into tokens, converts a token to an int or a double, and answers a whole line when that is what the program wants. It reads from a String, a File or System.in, which is why the first programs of this lesson need no terminal at all.
Tokens and lines
The scanner below reads a number, then a line, then the rest of the input. The second line of the output shows the space that the number left behind:
import java.util.Scanner;
public class Tokens {
public static void main(String[] args) {
Scanner scanner = new Scanner("36 Ada\n41 Alan");
int age = scanner.nextInt();
String name = scanner.nextLine();
System.out.println("age " + age);
System.out.println("name [" + name + "]");
String next = scanner.nextLine();
System.out.println("next [" + next + "]");
System.out.println("hasNext: " + scanner.hasNext());
scanner.close();
Scanner fixed = new Scanner("36 Ada\n41 Alan");
int first = fixed.nextInt();
fixed.nextLine();
String who = fixed.nextLine();
System.out.println("fixed " + first + " [" + who + "]");
fixed.close();
}
}
javac -Xlint:all Tokens.java
java Tokens
age 36
name [ Ada]
next [41 Alan]
hasNext: false
fixed 36 [41 Alan]
The newline nextInt leaves
nextInt reads the digits and stops at the space, so the nextLine that follows returns the rest of that line, which is Ada with a leading space. That is the bug every Java beginner meets, and there are two fixes: ask for a token with next instead of a line, or read and discard the rest of the line first. The second half of the program does the second, which is why the last line has no space and no leftover.
The rule to remember: nextInt, nextDouble and next stop before the end of the line, and nextLine returns everything up to and including that end. A program that mixes them must know which one it called last.
Standard input
System.in is the keyboard or, when the shell redirects, a file or the output of another program. The loop below reads lines until the stream ends, which is what hasNextLine reports:
import java.util.Scanner;
public class Stdin {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lines = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().strip();
lines++;
System.out.println(lines + ": " + line + " (" + line.length() + " chars)");
}
if (lines == 0) {
System.out.println("no input");
}
System.out.println("read " + lines + " lines");
scanner.close();
}
}
javac -Xlint:all Stdin.java
printf 'Ada 36\nGrace 45\n' | java Stdin
1: Ada 36 (6 chars)
2: Grace 45 (8 chars)
read 2 lines
The same program with no input at all ends at once, because hasNextLine answers false on an empty stream. That is the difference between a loop over hasNextLine and one over hasNext: the first is about lines, the second about tokens, and both stop at the end of the stream instead of waiting for a special value.
A menu loop
A program that reads commands is a loop over lines and a switch over the first word. The scanner here reads from a string, so the run on this page is the same every time; a real one would read System.in:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner scanner = new Scanner("add 2 3\nadd 10 5\nnonsense\nquit");
int total = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
switch (parts[0]) {
case "add" -> {
if (parts.length != 3) {
System.out.println("usage: add a b");
continue;
}
try {
total += Integer.parseInt(parts[1]) + Integer.parseInt(parts[2]);
System.out.println("total " + total);
} catch (NumberFormatException e) {
System.out.println("not a number: " + line);
}
}
case "quit" -> System.out.println("bye");
default -> System.out.println("unknown command: " + parts[0]);
}
}
scanner.close();
System.out.println("final " + total);
}
}
javac -Xlint:all Menu.java
java Menu
total 5
total 20
unknown command: nonsense
bye
final 20
The switch is the arrow form of lesson 014, the continue belongs to the enclosing loop, and the try is the one of lesson 096. A command loop is where those three meet: the text is split, the first word chooses a branch, and a number that does not parse is reported without ending the program.
Closing a Scanner
A Scanner is a resource, so it belongs in a try-with-resources, and close on a scanner over a String only releases its own buffer. On System.in the close closes the standard input as well, which is why a program that reads the keyboard and then wants to read it again should not close the scanner, or should wrap the stream so that the close does not reach it.
The classes of the next lessons are the alternative for a file: lesson 105 reads a text file with Files, which needs no scanner at all. A scanner is at its best when the input is tokens of a known type, and a line-based reader is at its best when the unit is the line.
Exercises
- Read a name and an age from one line with next() twice and print them.
- Count the words of a text with a scanner and hasNext.
- Add a sum command to the menu that adds every remaining number of the line.
- Print the average of a list of numbers read from standard input, with EOF as the end of the input.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
nextLinereturn after anextInt?Answer
The rest of the line the number was on, including its leading space
nextInt stops at the end of the number, and the line continues from there.
-
Which method reports that standard input has ended?
Answer
hasNextLine, which answers false at the end of the stream
The loop over hasNextLine ends when the stream has no more lines to read.
-
Why is closing a Scanner on System.in a decision?
Answer
It closes the standard input, so nothing else can read it
The scanner closes the stream it was given, and System.in belongs to the whole program.
-
What does this program print?
import java.util.Scanner; public class Q1 { public static void main(String[] args) { Scanner s = new Scanner("10 20\n30"); int a = s.nextInt(); int b = s.nextInt(); String rest = s.nextLine(); System.out.println(a + b); System.out.println("[" + rest + "]"); } }Answer
30 / []
The two ints use the first line, so the next line call gets the empty rest of it.
-
Which two methods read a line and a token?
Answer
nextLine and next
next returns one whitespace-separated token, and nextLine returns the rest of the line.
-
What does a Scanner split the input on by default?
Answer
Whitespace, which is why next reads one word
The delimiter is whitespace, and useDelimiter replaces it.
-
Why does the menu read from a String on this page?
Answer
So the run is the same every time and the output on the page is the real one
A scanner over a string exercises the same code, and the sample input is in the program.
-
What does this program print?
import java.util.Scanner; public class Q2 { public static void main(String[] args) { Scanner s = new Scanner("a b c"); int n = 0; while (s.hasNext()) { s.next(); n++; } System.out.println(n); } }Answer
3
The scanner has three tokens, and the loop counts one per next call.
-
What does this program print?
import java.util.Scanner; public class Q3 { public static void main(String[] args) { Scanner s = new Scanner("7\n8"); int first = s.nextInt(); s.nextLine(); String second = s.nextLine(); System.out.println(first + Integer.parseInt(second)); } }Answer
15
The nextLine clears the rest of the first line, so the second line is the number 8.
-
What is the risk of closing a Scanner over System.in?
Answer
A later read of the standard input finds the stream closed
The close reaches the underlying stream, which the whole program shares.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev