Sub topic 2
Creating a Scanner
This chapter assumes you can compile and run a Java program from the command line and write basic classes and methods. It also assumes you know what String, int and exceptions are. Here you will create a java.util.Scanner on standard input, see what it does internally, and learn the construction mistakes that cause trouble later.
What a Scanner is
System.in is an InputStream. It delivers raw bytes and offers only low-level read methods. You could decode those bytes into characters, find line ends and parse numbers yourself, but that is tedious.
A Scanner does this work for you. It wraps a source of text and provides three things:
- Decoding. It converts bytes to characters using a charset.
- Buffering. It reads ahead in chunks instead of one byte at a time.
- Parsing. It splits the text into tokens and converts them to
int,double,boolean,BigIntegerand other types.
The next chapters cover the reading methods in detail. This chapter is about the object and how you build it.
In a normal terminal the line is sent to your program only after the user presses Enter. Until then the text sits in the terminal's line editor, so your program does not see partial lines.
The standard construction
The usual form is one line:
Scanner in = new Scanner(System.in);Creating the Scanner does not read anything and does not wait for input. The program blocks later, at the first call such as nextLine(), if no data is available yet.
Here is a complete program, the first example of this tutorial:
import java.util.Scanner;
public class Greeter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.print("Age: ");
int age = in.nextInt();
System.out.println(name + " is " + age);
}
}Compile and run it. The text after each prompt is what the user types:
$ javac Greeter.java
$ java Greeter
Name: Ada Lovelace
Age: 36
Ada Lovelace is 36Three details to notice:
import java.util.Scanner;is required becauseScanneris not injava.lang.nextLine()returned the whole line, including the space inside the name.nextInt()read one integer token. Reading a line and then a number works here. The reverse order has a pitfall, covered in a later chapter.
Constructors you will meet
Scanner can read from many sources, not only System.in. The source decides what the Scanner treats as the end of input.
| Constructor | Reads from | Typical use |
|---|---|---|
| `Scanner(InputStream)` | Bytes, decoded with the default charset | `System.in` |
| `Scanner(InputStream, Charset)` | Bytes, decoded with the charset you choose | Console input with a known encoding |
| `Scanner(String)` | The characters of a string | Tests, parsing a line already in memory |
| `Scanner(File)` or `Scanner(Path)` | A file | Reading data files (throws `IOException` for `Path`, `FileNotFoundException` for `File`) |
| `Scanner(Readable)` | Any `Readable`, such as a `Reader` | Input you have already wrapped |
Two of these are especially useful. The Scanner(String) constructor lets you try parsing without a keyboard:
import java.util.Scanner;
public class StringScanner {
public static void main(String[] args) {
Scanner in = new Scanner("Ada 36");
String name = in.next();
int age = in.nextInt();
System.out.println(name + " is " + age);
}
}This prints Ada is 36. Because the input is fixed, the program behaves the same on every run. That makes a method that takes a Scanner parameter easy to test, as shown later in this chapter.
The charset constructor matters when your input contains non-ASCII characters:
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Utf8Input {
public static void main(String[] args) {
Scanner in = new Scanner(System.in, StandardCharsets.UTF_8);
System.out.print("City: ");
String city = in.nextLine();
System.out.println("Length: " + city.length());
}
}Scanner(InputStream, Charset) exists since Java 10. Older code uses Scanner(InputStream, String) with a charset name such as "UTF-8". That version throws IllegalArgumentException if the name is unknown.
What the Scanner does with the text
Understanding the internals explains most of the surprises you will see.
Delimiters and tokens
By default a Scanner treats whitespace (spaces, tabs and line terminators) as the separator between tokens. For the input 12 7\n, nextInt() returns 12 and the next nextInt() returns 7. The extra spaces vanish because the separator pattern matches any run of whitespace. You can change the separator, and a later chapter shows how.
Locale
A Scanner also has a locale. It decides which number formats are accepted. 1,5 can be a valid double in a German locale and invalid in a US locale. The Scanner uses the default locale of the JVM, so the same program can accept different input on different machines. To make the behavior fixed, set it:
import java.util.Locale;
import java.util.Scanner;
public class FixedLocale {
public static void main(String[] args) {
Scanner in = new Scanner(System.in).useLocale(Locale.US);
System.out.print("Price: ");
double price = in.nextDouble();
System.out.println("Price is " + price);
}
}useLocale returns the same Scanner, so the call chains onto the constructor. With Locale.US, typing 12.50 gives 12.5, and typing 12,50 fails with an InputMismatchException.
Look-ahead buffering
A Scanner does not read one character at a time. It fills an internal buffer from the underlying stream, and it may read more than your program has consumed. This one fact leads to the most important rule of this chapter.
One Scanner per input stream
Create one Scanner for System.in and share it. Do not create a new one each time you need input.
Suppose two Scanners wrap the same stream:
import java.util.Scanner;
public class TwoScanners {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int first = a.nextInt();
Scanner b = new Scanner(System.in);
int second = b.nextInt();
System.out.println(first + " " + second);
}
}Run it with the input on one stream, for example printf '1 2\n' | java TwoScanners. Scanner a reads the whole available chunk into its own buffer and returns the first token. Scanner b then asks System.in for more bytes, and none are left. Typically b.nextInt() throws NoSuchElementException, even though the text 2 was in the input. The data is not lost from the system. It sits in a's buffer, where b cannot reach it.
At a keyboard, the program may seem to work because the terminal delivers one line at a time. That makes the bug appear only when input is redirected from a file or pipe, such as in an automated test or an online judge.
The same mistake appears in helper methods:
import java.util.Scanner;
public class HelperMistake {
// Wrong: a new Scanner on every call
static int readIntBad() {
return new Scanner(System.in).nextInt();
}
// Right: the caller owns the Scanner
static int readInt(Scanner in) {
return in.nextInt();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = readInt(in);
int b = readInt(in);
System.out.println(a + b);
}
}Passing the Scanner as a parameter has a second benefit. A test can call readInt(new Scanner("40 2")) without touching the keyboard.
You have two reasonable ways to share a Scanner:
- Create it in
mainand pass it to the methods that need it. - Keep it in a
private static final Scannerfield of the class.
The first is easier to test. The second is shorter in small programs. In either case, do not let several classes each create their own Scanner on System.in.
Errors that come from construction
Most constructor problems are compile-time or setup problems, not runtime ones:
- Missing import. The compiler reports
cannot find symbolforScanner. Addimport java.util.Scanner;. - Checked exceptions for files.
new Scanner(new File("data.txt"))throwsFileNotFoundException. You must catch it or declare it.new Scanner(System.in)throws no checked exception, which is why console examples need notry/catcharound construction. - Unknown charset name. The old string-based charset constructor throws
IllegalArgumentException. TheCharsetconstructor cannot fail this way. - Unused-resource warnings. Some IDEs warn that the Scanner is never closed. Whether to close a Scanner on
System.inis a separate decision, and a later chapter explains why closing it has a side effect.
Checking your setup
When something behaves oddly, test the Scanner with fixed input. Replace System.in with a string, run the same logic, and compare. If the string version works, the problem is in how the real input arrives: the terminal, the redirection, the charset or the locale. If the string version also fails, the problem is in your reading logic.
You can also redirect a file into your program from the shell, with java Greeter < input.txt. The Scanner sees the file's bytes through System.in. A file ends the stream when the bytes run out, so you can test end-of-input behavior without pressing a key combination.
Summary of rules
- Build the Scanner with
new Scanner(System.in). Construction never blocks. - Share one Scanner per input stream. A second Scanner on the same stream can lose data that the first has buffered.
- Choose the charset and locale explicitly when your program must behave the same everywhere.
- Prefer passing a
Scannerto methods. You can then test them withnew Scanner(String).
Exercise
A program has two methods, askAge() and askName(). Each one runs Scanner in = new Scanner(System.in); and reads one value. It works when you type the answers by hand, but fails with NoSuchElementException when you run printf '36\nAda\n' | java App. Explain why, and give the fix.
Show answer
The first Scanner reads the available piped bytes into its internal buffer and returns only the first value. The second Scanner then finds nothing left in System.in, because the second line is in the first Scanner's buffer. Typing by hand hides the problem because the terminal delivers one line at a time. The fix is to create one Scanner in main (or a static field) and pass it to both methods.
Exercise
Write a method static int sumOfTwo(Scanner in) that returns the sum of the next two integers from the Scanner. Then show a one-line call that tests it without a keyboard and prints 42.
Show answer
static int sumOfTwo(Scanner in) { return in.nextInt() + in.nextInt(); } and the test call is System.out.println(sumOfTwo(new Scanner("40 2"))); The Scanner(String) constructor supplies fixed input, so the result is always 42.
Exercise
Why might new Scanner(System.in).nextDouble() accept 3,14 on one computer but reject it on another? Name two ways to make the behavior consistent.
Show answer
The Scanner uses the JVM's default locale to decide which number format is valid, and a locale that uses a decimal comma accepts 3,14. To make it consistent, call useLocale(Locale.US) (or another fixed locale) on the Scanner, or read the text as a token and parse it yourself with a known format.