Coding the validation checks conceptually introduced in 11.2.7, plus using exception handling to gracefully manage runtime errors.
Reasons for data validation: to prevent erroneous/invalid data from ever entering the system in the first place, protecting the accuracy and reliability of the program's data.
Example
try { int number = Integer.parseInt(userInput); } catch (NumberFormatException e) { System.out.println("Please enter a valid whole number."); }
Coding the full set of validation checks (from 11.2.7), typically using a loop that keeps prompting the user until valid input is provided:
| Check | Example condition (pseudocode) |
|---|---|
| Presence check | input != "" |
| Range check | value >= min AND value <= max |
| Uniqueness check | value not already in existing records |
| Length check | input.length() == expectedLength |
| Type check | handled via exception handling when parsing, e.g. catching NumberFormatException |
| Logical check | endDate > startDate |
| Check digit | recalculated digit matches the supplied check digit |
| Checksum | recalculated checksum matches the expected value |
Example
// Range check with a validation loop int age; do { System.out.print("Enter age (0-120): "); age = scanner.nextInt(); } while (age < 0 || age > 120);
💡 Exam Tip
A validation loop should re-prompt until valid data is given, using a post-check loop (do-while) since you need to get the input at least once before you can check it.