Validating User Input
Handle invalid input gracefully.
Never Trust Input
Users type wrong things: letters where numbers belong, blanks, or out-of-range values. Robust programs validate input and ask again instead of crashing.
This lesson shows graceful validation patterns with Scanner.
Check Before You Read
The simplest guard is hasNextInt(). Read the integer only when one is actually available.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner("42");
if (scanner.hasNextInt()) {
System.out.println("Got: " + scanner.nextInt());
} else {
System.out.println("Please enter a number");
}
scanner.close();
}
}All lessons in this course
- Reading Input with Scanner
- Reading Numbers and Lines
- Validating User Input
- BufferedReader Alternative