Sub topic 3
Reading numbers and words
What this chapter assumes
You should already know how to create a Scanner on System.in (the previous chapter) and how try/catch works. This chapter covers the token methods: next, nextInt, nextDouble and their relatives. You will learn how they split input, how they convert text to values, and which errors they produce. Whole-line reading, the leftover-newline pitfall and full input validation get their own chapters. This one only points toward them.
What a token is
A Scanner does not look at input one character at a time. It splits the input into tokens. A token is a run of characters between delimiters. The default delimiter is any run of whitespace: spaces, tabs and line breaks.
Two consequences follow:
- The token methods ignore how the user spaces things out.
apple 3 1.50on one line and the same three values on three lines produce the same tokens. - A token never contains whitespace.
next()cannot returnNew Yorkas one value. It returnsNewand thenYork.
The token methods
Each method skips leading delimiters, takes the next token, and tries to convert it.
| Method | Returns | Accepts |
|---|---|---|
| `next()` | `String` | Any token |
| `nextInt()` | `int` | An integer such as `42`, `-7` or `+5` |
| `nextLong()` | `long` | An integer that fits in a `long` |
| `nextDouble()` | `double` | A decimal such as `3.14`, or an integer such as `5` |
| `nextBoolean()` | `boolean` | `true` or `false`, in any letter case |
| `nextBigDecimal()` | `BigDecimal` | A decimal, with no rounding error |
The first example reads one word, one integer and one decimal:
import java.util.Scanner;
public class Tokens {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String item = in.next();
int count = in.nextInt();
double price = in.nextDouble();
System.out.println(count + " x " + item + " at " + price);
System.out.println("Total: " + count * price);
}
}Type apple 3 1.50 and press Enter. The program prints 3 x apple at 1.5 and Total: 4.5. You get the same result if you type each value on its own line.
Reading several values in a loop
Because tokens ignore line layout, one loop can read a list of values. This program reads a count, then that many numbers, and prints their average:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many numbers? ");
int n = in.nextInt();
double sum = 0;
for (int i = 1; i <= n; i++) {
System.out.print("Number " + i + ": ");
sum += in.nextDouble();
}
System.out.println("Average: " + (n == 0 ? 0 : sum / n));
}
}You can paste 3 10 20 30 as one line. The program still prints every prompt, but it never waits, because the tokens are already available.
Conversion rules worth knowing
Integers and decimals are not interchangeable
nextDouble() accepts 5 and returns 5.0. nextInt() does not accept 5.0 or 5.5. It throws an exception even though the leading 5 looks fine, because the whole token must be a valid integer.
nextInt() also accepts a signed value such as +5. In an English-language locale it accepts group separators, so 1,000 is read as 1000. Do not rely on this if your users might type commas for another reason.
For bases other than ten, pass a radix: in.nextInt(2) reads 101 as 5, and in.nextInt(16) reads ff as 255.
Decimal parsing depends on the locale
Scanner parses numbers using the default locale for formatting. On a machine set to a German or French locale, nextDouble() expects a decimal comma. It reads 3,14 and rejects 3.14. The same program then behaves differently on two computers.
To make the behavior predictable, set the locale explicitly:
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("Radius: ");
double r = in.nextDouble();
System.out.println("Area: " + Math.PI * r * r);
}
}useLocale returns the same Scanner, so you can chain it onto the constructor call. Use Locale.US or Locale.ROOT for scripts and tests. Use the default locale when the program is meant for people who type numbers in their own format.
Money needs `BigDecimal`
double stores binary approximations. 0.1 + 0.2 is not exactly 0.3. For prices and other exact decimal values, read with nextBigDecimal():
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Scanner;
public class Invoice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in).useLocale(Locale.US);
BigDecimal a = in.nextBigDecimal();
BigDecimal b = in.nextBigDecimal();
System.out.println("Sum: " + a.add(b));
}
}Input 0.1 0.2 prints Sum: 0.3.
What happens when a token does not fit
InputMismatchException
If the next token cannot be converted, the method throws java.util.InputMismatchException. Typing abc where nextInt() expects a number triggers it.
The important detail is that a failed conversion does not consume the token. The Scanner stays positioned in front of the bad token. The following program reads one integer and reports a bad token:
import java.util.InputMismatchException;
import java.util.Scanner;
public class OneInt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Age: ");
try {
int age = in.nextInt();
System.out.println("Next year you will be " + (age + 1));
} catch (InputMismatchException e) {
String bad = in.next();
System.out.println("Not an integer: " + bad);
}
}
}The in.next() call in the catch block removes the bad token. Without it, the token would still be waiting for the next read.
NoSuchElementException
If the input ends before a token is available, the methods throw java.util.NoSuchElementException. This happens when the user presses Ctrl+D (Ctrl+Z then Enter on Windows) or when a program reads from a file or pipe with too few values.
InputMismatchException is a subclass of NoSuchElementException. If you catch both, put InputMismatchException first. If you catch the parent first, the child handler can never run, and the compiler rejects the code.
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TwoErrors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
} catch (InputMismatchException e) {
System.out.println("A value was not an integer");
} catch (NoSuchElementException e) {
System.out.println("Input ended early");
}
}
}Both exceptions are unchecked, so Java does not force you to catch them. An uncaught one ends the program with a stack trace.
Mixing tokens and lines
Token methods stop right after the token. They do not consume the line break that follows it. If you call nextInt() and then nextLine(), the nextLine() call returns the empty remainder of the first line instead of waiting for new input. The next two chapters explain this in detail and show the fix. Until then, avoid mixing the two kinds of read. If you only need tokens, use only token methods.
When tokens are the wrong tool
Tokens suit input made of simple values separated by whitespace: numbers, flags, single words. They are a poor fit when:
- A value can contain spaces, such as a full name or a book title. Use a line read.
- Empty input is meaningful. Tokens cannot represent an empty value, because consecutive whitespace is one delimiter.
- The format uses another separator, such as commas. A custom delimiter can handle that, and a later chapter covers it.
Common mistakes
- Expecting
next()to return a whole phrase. It returns one whitespace-free token. - Reading
3.5withnextInt(). UsenextDouble(), or read aStringand convert it yourself. - Assuming
nextDouble()accepts a period everywhere. In some locales it requires a comma. - Catching
InputMismatchExceptionand retrying without consuming the token. - Reading more values than the user supplied and getting
NoSuchElementException. - Using
doublefor money values.
Exercise
A program calls int a = in.nextInt(); and the user types 12abc. What happens, and what is the state of the Scanner afterward? What single call in the catch block lets the program move on?
Show answer
12abc is one token because it contains no whitespace, and it is not a valid integer, so nextInt() throws InputMismatchException. The token is not consumed, so the Scanner is still positioned before 12abc. Calling in.next() in the catch block removes that token, and the next read starts after it.
Exercise
A program reads a price with in.nextDouble() and works on your computer with the input 2.75. On a colleague's computer set to a German locale, it throws InputMismatchException for the same input. Why does this happen, and how do you make the program behave the same on both computers?
Show answer
Scanner parses numbers with the default locale. The German locale uses a decimal comma, so it rejects 2.75. Call useLocale(Locale.US) on the Scanner, for example new Scanner(System.in).useLocale(Locale.US), so it always expects a decimal point.
Exercise
The user types 7 apples and presses Enter. Write the two read calls that store 7 in an int named count and apples in a String named word, using the same Scanner in.
Show answer
int count = in.nextInt(); followed by String word = in.next();. The tokens are 7 and apples, and they are read in order.