Sub topic 6
Validating Input
This chapter assumes that you know basic Java syntax, can compile and run a program, and understand Scanner, variables, loops, and exceptions. The goal is to reject invalid input without crashing or getting stuck in an endless loop.
Check before consuming input
A Scanner reads tokens from System.in. A token is a separate piece of input, usually separated by whitespace. For example, the input 42 apples contains two tokens.
The hasNextInt method checks whether the next token can be converted to an int. It does not consume the token. The nextInt method both reads and converts it.
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 whole number: " + in.next());
System.out.print(prompt);
}
return in.nextInt();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = readInt(in, "Enter your age: ");
System.out.println("Age: " + age);
}
}If the user enters abc, hasNextInt returns false. The call to next() then consumes abc, so the next loop iteration can inspect new input. Without consuming the bad token, the loop would inspect the same invalid token forever.
hasNextInt accepts values that Java can represent as an integer. It rejects decimal input such as 12.5, text such as ten, and values outside the int range.
Catch `InputMismatchException`
You can also call nextInt directly and handle the exception that it throws for an invalid token. InputMismatchException is an exception that indicates that the next token has the wrong type.
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckedInt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a quantity: ");
try {
int quantity = in.nextInt();
System.out.println("Quantity: " + quantity);
} catch (InputMismatchException ex) {
System.out.println("Please enter a whole number.");
}
}
}After nextInt throws, the invalid token remains in the scanner. Therefore, a retry loop must consume that token before trying again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class RetriedInt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter a number: ");
try {
number = in.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println("That is not an integer.");
in.next();
}
}
System.out.println("You entered " + number);
}
}For simple checks, hasNextInt makes the normal path clear. Exception handling is useful when invalid input represents an unusual condition or when several operations may fail together.
Validate more than the type
A correctly typed value can still be unacceptable. For example, -3 is an integer but might not be a valid quantity.
int quantity = readInt(in, "Quantity: ");
while (quantity < 0) {
System.out.println("Quantity cannot be negative.");
quantity = readInt(in, "Quantity: ");
}Use a separate condition for business rules such as ranges, required values, or allowed choices. Type validation answers “Can Java read this as an integer?” Domain validation answers “Is this integer acceptable for this program?”
> callout note > Always decide what should happen when input ends. Interactive input can end when a redirected file has no more data or when the user sends an end-of-file signal. hasNextInt alone does not distinguish an invalid token from unavailable future input.
| Check | Meaning | Consumes input? |
|---|---|---|
| `hasNextInt()` | The next token is an integer | No |
| `nextInt()` | Read the next integer | Yes, if valid |
| `hasNext()` | Some token remains | No |
| `next()` | Read the next token as text | Yes |
Exercise
Why must a retry loop call next() after hasNextInt() returns false?
Show answer
It must consume the invalid token. Otherwise, every iteration checks the same token and the loop never makes progress.