Input Validation

Never Trust Input

Users type wrong things. If the input is not a number, nextInt() throws InputMismatchException. Check first with hasNextInt().

Example

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("abc\n-4\n150\n42\n");
        int age = -1;
        while (true) {
            if (!sc.hasNextInt()) {
                System.out.println("'" + sc.next() + "' is not a number, try again");
                continue;
            }
            int value = sc.nextInt();
            if (value < 1 || value > 120) {
                System.out.println(value + " is out of range (1-120), try again");
                continue;
            }
            age = value;
            break;
        }
        System.out.println("Valid age: " + age);
    }
}

Output

'abc' is not a number, try again
-4 is out of range (1-120), try again
150 is out of range (1-120), try again
Valid age: 42

Other Input Sources

  • Command-line arguments: java Main.java Asha 22 fills args with ["Asha", "22"].
  • BufferedReader: faster for large inputs (competitive programming).
  • Web apps: input comes from HTTP requests (forms, JSON), not from Scanner. Spring Boot converts it for you.
// competitive programming style fast input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] parts = br.readLine().split(" ");