Sub topic 6
Validating input
Users type things your program does not expect. A letter appears where a number belongs, a line is blank, or a value is out of range. This chapter shows how to check input before you use it, and how to recover when the check fails.
This chapter assumes you can create a Scanner on System.in. It also assumes you know the difference between token reads (next, nextInt) and line reads (nextLine), and that you can use try/catch. The leftover-newline pitfall from the previous chapter still applies here.
What goes wrong without validation
Consider the simplest numeric read:
import java.util.Scanner;
public class Unchecked {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Age: ");
int age = in.nextInt();
System.out.println("Next year you will be " + (age + 1));
}
}If the user types abc, the program stops with java.util.InputMismatchException. The exception is unchecked, so the compiler does not force you to deal with it.
The failure has a second consequence that matters more. When nextInt throws, it does not consume the bad token. The scanner's position stays in front of abc. If you catch the exception and call nextInt again, it fails again on the same token, forever.
Two ways to validate
You have two approaches, and both appear in real code:
- Look before you read. Call
hasNextInt()(orhasNextDouble(), and so on) to test the next token without consuming it. Then read it only if the test passes. - Read and catch. Call
nextInt()insidetry, catchInputMismatchException, and discard the bad token yourself.
Look before you read: hasNextInt
The hasNextXxx methods return a boolean and leave the input untouched. This is the safer default because the control flow is ordinary if and while, not exceptions.
import java.util.Scanner;
public class SafeInt {
static int readInt(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
if (!in.hasNext()) {
throw new IllegalStateException("Input ended");
}
System.out.println("Not a number: " + in.next());
System.out.print(prompt);
}
return in.nextInt();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = readInt(in, "Enter a number: ");
System.out.println("You entered " + n);
}
}Here is how the loop behaves:
hasNextInt()waits for a token. On an interactive console it blocks until the user presses Enter.- If the token is not an integer,
hasNextInt()returnsfalseand the loop body runs. hasNext()checks whether any token is left. If none is left, the input has ended, and no further typing can fix the problem. Without this check the loop would never end. The method throws instead.in.next()consumes and prints the bad token. Consuming it is what lets the nexthasNextInt()look at fresh input.- When the loop exits, the next token is known to be an integer, so
nextInt()cannot throw anInputMismatchException.
The diagram shows the same loop as a decision flow.
Read and catch: InputMismatchException
The same behavior with exceptions looks like this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchInt {
static int readInt(Scanner in, String prompt) {
while (true) {
System.out.print(prompt);
try {
return in.nextInt();
} catch (InputMismatchException e) {
System.out.println("Not a number: " + in.next());
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = readInt(in, "Enter a number: ");
System.out.println("You entered " + n);
}
}The call to in.next() inside the catch block is essential. It removes the token that nextInt refused to consume. Remove it and the loop spins forever, printing the prompt again and again.
There is one more trap in this version. InputMismatchException is a subclass of NoSuchElementException. If the input ends, nextInt() throws a plain NoSuchElementException, and the catch (InputMismatchException e) block does not catch it. That is usually what you want, because the loop would otherwise never finish. If you add a second catch for NoSuchElementException, put the more specific InputMismatchException first. The compiler rejects the reverse order.
Which one to choose
| Criterion | `hasNextInt` loop | `try`/`catch` loop |
|---|---|---|
| Normal bad input handled with | `if` and `while` | exception |
| End of input | Easy to test with `hasNext` | Arrives as `NoSuchElementException` |
| Token must be discarded | Yes, with `next()` | Yes, with `next()` in the `catch` |
| Readability for several checks | Good | Gets nested quickly |
Bad input from a user is an expected event, not an exceptional one. For that reason hasNextXxx is the better default. The catch style is still useful when a single read sits deep in code that already uses exception handling.
Validating the value, not only the type
An integer can still be wrong. An age of -5 or 900 parses fine but makes no sense. Type validation and range validation are separate steps, and a reusable method can combine them:
import java.util.Scanner;
public class RangeInt {
static int readIntInRange(Scanner in, String prompt, int min, int max) {
while (true) {
System.out.print(prompt);
if (!in.hasNext()) {
throw new IllegalStateException("Input ended");
}
if (!in.hasNextInt()) {
System.out.println("Not a whole number: " + in.next());
continue;
}
int value = in.nextInt();
if (value >= min && value <= max) {
return value;
}
System.out.println(value + " is outside " + min + " to " + max);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = readIntInRange(in, "Age (0-120): ", 0, 120);
System.out.println("Age accepted: " + age);
}
}The order of the checks matters. The method tests hasNext() first so that exhausted input is reported once, clearly. It then tests the type. It tests the range only after a value has been read successfully.
Running it with the input abc, -3, 42 on separate lines produces:
Age (0-120): Not a whole number: abc
Age (0-120): -3 is outside 0 to 120
Age (0-120): Age accepted: 42(With a piped file the prompts appear back to back, as shown. At a keyboard the user's typing is interleaved.)
Behavior you might not expect
Out-of-range numbers are also mismatches
hasNextInt() returns false for a token such as 99999999999, which looks like an integer but does not fit in an int. nextInt() throws InputMismatchException for it too. If you need larger values, use hasNextLong() and nextLong(), or hasNextBigInteger().
Validation depends on the locale
A Scanner uses the default locale when it decides what a number looks like. In a US locale, 1,000 is a valid int (the comma is a grouping separator) and 3.5 is a valid double. In a German locale, 3,5 is valid and 3.5 is not. If your program must behave identically on every machine, call in.useLocale(java.util.Locale.ROOT) right after creating the scanner. You can also read each value as a string and parse it yourself.
Blank lines are invisible to token reads
Token reads skip whitespace, including empty lines. If the user presses Enter without typing anything, hasNextInt() keeps waiting for a token. The prompt is not repeated, and the user sees nothing happen. If blank input must be handled as a distinct case, switch to line-based validation (see below).
hasNextInt can block
hasNextXxx methods may block exactly like nextXxx. This is correct behavior: the scanner cannot judge a token that has not arrived. It becomes a problem only if you expect hasNextInt() to return false immediately when the user has typed nothing.
Line-based validation
Validating by line gives you control over the whole text the user typed, including blank lines and trailing spaces. You read with nextLine() and convert it yourself with Integer.parseInt, which throws NumberFormatException on bad text.
import java.util.Scanner;
public class LineInt {
static int readInt(Scanner in, String prompt) {
while (true) {
System.out.print(prompt);
if (!in.hasNextLine()) {
throw new IllegalStateException("Input ended");
}
String line = in.nextLine().trim();
if (line.isEmpty()) {
System.out.println("Please type something.");
continue;
}
try {
return Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("Not a whole number: " + line);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = readInt(in, "Enter a number: ");
System.out.println("You entered " + n);
}
}This version has three advantages:
- No token left behind.
nextLine()always consumes the whole line, so no bad token stays in the input. - No leftover newline. If every read in the program is a
nextLine(), the mixing pitfall from the previous chapter cannot occur. - Blank lines are visible. The program can answer them with a message.
The cost is that you now parse numbers yourself, and Integer.parseInt rejects things the Scanner would accept, such as 1,000. Neither behavior is wrong. Pick one and apply it consistently.
Common errors
- Infinite loop on bad input. The bad token is never consumed. Call
next()(ornextLine()) in the failure path. - Calling
nextInt()without testing first, then catching nothing. The program crashes withInputMismatchExceptionon the first stray letter. - Catching
Exceptionbroadly. This hidesNoSuchElementExceptionat end of input, so the retry loop never ends when the input comes from a file or pipe. - Forgetting the range check. A well-formed number is not necessarily a valid one.
- Creating a new
Scannerinside the loop. Each new scanner may buffer input that the previous one already read, so tokens can be lost. Create one scanner and pass it to your methods.
Exercise
A student writes this loop and finds that typing "abc" makes the program print "Try again" forever. Why does it happen, and what one-line change fixes it? while (true) { try { int n = in.nextInt(); System.out.println("Got " + n); break; } catch (java.util.InputMismatchException e) { System.out.println("Try again"); } }
Show answer
nextInt() throws InputMismatchException but does not consume the token "abc". Each pass through the loop reads the same token and fails again. Add in.next(); (or in.nextLine();) inside the catch block so the bad token is discarded before the next attempt.
Exercise
Write the body of a method double readPositive(Scanner in) that keeps asking until the user types a double greater than zero, and throws IllegalStateException if the input ends. Which three checks does it need, and in what order?
Show answer
Check in this order: (1) in.hasNext(), so that ended input throws IllegalStateException; (2) in.hasNextDouble(), and if false, discard the token with in.next() and ask again; (3) after reading the value with in.nextDouble(), test value > 0, and ask again if it is not. The structure matches readIntInRange in this chapter, with hasNextDouble and nextDouble in place of the int methods.
Exercise
You switch a program from nextInt() with hasNextInt() checks to nextLine() with Integer.parseInt. Name one input that behaves differently, and say how.
Show answer
An empty line. With hasNextInt() the scanner skips it and keeps waiting for a token, so the user sees no response. With nextLine() the program receives "", can detect it with isEmpty(), and can print a message. Another valid answer is "1,000": a Scanner in a US locale accepts it as 1000, but Integer.parseInt throws NumberFormatException.