0Pricing
Java Academy · Lesson

Validating User Input

Handle invalid input gracefully.

Validating User Input is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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();
    }
}

Looping Until Valid

A retry loop keeps asking until a valid integer arrives. When the token is wrong, discard it with next() and continue.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("abc xyz 50");
        int value = -1;
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                value = scanner.nextInt();
                break;
            }
            scanner.next();
        }
        System.out.println("Accepted: " + value);
        scanner.close();
    }
}

Range Checking

Beyond type, values often must fall within a range. Read the number, then verify it before accepting.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("7");
        int n = scanner.nextInt();
        if (n >= 1 && n <= 10) {
            System.out.println("Valid: " + n);
        } else {
            System.out.println("Out of range");
        }
        scanner.close();
    }
}

Try-Catch on Parsing

An alternative reads a whole line then parses it, catching NumberFormatException for invalid text. This keeps the buffer simple.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("notanumber");
        String line = scanner.nextLine();
        try {
            int n = Integer.parseInt(line.trim());
            System.out.println("Parsed: " + n);
        } catch (NumberFormatException e) {
            System.out.println("Invalid number: " + line);
        }
        scanner.close();
    }
}

Validating Non-Empty Text

For text input, reject blanks. isBlank() returns true for empty or whitespace-only strings.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("   ");
        String name = scanner.nextLine();
        if (name.isBlank()) {
            System.out.println("Name cannot be empty");
        } else {
            System.out.println("Hello, " + name);
        }
        scanner.close();
    }
}

Validating a Choice

For menu choices, confirm the value is one of the allowed options before acting on it.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("y");
        String choice = scanner.next().toLowerCase();
        if (choice.equals("y") || choice.equals("n")) {
            System.out.println("You chose: " + choice);
        } else {
            System.out.println("Please enter y or n");
        }
        scanner.close();
    }
}

A Reusable Validator Method

Extract validation into a method so the logic is reused. Here a method checks an age is within a sensible range.

public class Main {
    static boolean isValidAge(int age) {
        return age >= 0 && age <= 120;
    }

    public static void main(String[] args) {
        System.out.println(isValidAge(30));
        System.out.println(isValidAge(-5));
    }
}

Combining Type and Range

Real validation often combines a type check, a range check, and a retry loop into one robust routine.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner("abc 200 45");
        int valid = -1;
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                int n = scanner.nextInt();
                if (n >= 1 && n <= 100) {
                    valid = n;
                    break;
                }
            } else {
                scanner.next();
            }
        }
        System.out.println("Final: " + valid);
        scanner.close();
    }
}

Clear Error Messages

Good validation also gives the user helpful feedback. Tell them exactly what was wrong and what is expected, rather than a generic failure.

public class Main {
    static String validate(String input) {
        if (input.isBlank()) return "Input is empty";
        if (!input.matches("\\d+")) return "Only digits allowed";
        return "OK";
    }

    public static void main(String[] args) {
        System.out.println(validate(""));
        System.out.println(validate("12a"));
        System.out.println(validate("123"));
    }
}

Validation Strategy

Check the type with the hasNext family or try-catch, check the range and emptiness, loop until valid, and always explain errors clearly.

Quick Check

Test your input validation knowledge.

Recap

You learned to validate input gracefully:

  • Guard with hasNextInt or parse inside a try-catch
  • Use retry loops, discarding bad tokens with next()
  • Check ranges and reject blank text with isBlank
  • Extract reusable validator methods
  • Give clear, specific error messages

Frequently asked questions

Is the “Validating User Input” lesson free?

Yes — the full text of “Validating User Input” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Validating User Input”?

Handle invalid input gracefully. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Validating User Input” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Input with Scanner
  2. Reading Numbers and Lines
  3. Validating User Input
  4. BufferedReader Alternative
← Back to Java Academy