5.12 Problems and Solutions
In the previous lesson we built a small program that reads a name and a birth year with Scanner. The program works, but it does not guard against bad input. If the user types -20 as a birth year, the program happily computes an age of 2041, which is clearly wrong. The fix is to validate the input before using it.
Range check on the age
Right after computing age = 2021 - birthYear, we add a condition: if (age >= 0 && age <= 100). Inside the block we display the result; in the matching else branch we print an error like "birth year invalid". With -20 the condition fails and we see the error message.
Reject non-numeric input
- Before reading the integer, call
boolean hasNextInt = scanner.hasNextInt();. hasNextInt()peeks at the next token and returnstrueonly if it looks like an integer.- Wrap the rest of the logic in
if (hasNextInt) { ... }, and use the matchingelsebranch to print "unable to parse the birth year".
Running the new version and entering a letter triggers the error message instead of crashing the program. Combined with the range check, we now have a small but robust input loop. This pattern of "look first, then read" is general: every external input should be validated before it is trusted.
Summary
This lesson demonstrates common input validation problems when a user enters name and age data. It covers two key solutions: validating that age falls within a realistic range (0-100) using conditional statements, and using the hasNextInt() Scanner method to ensure the user enters an integer rather than letters or other invalid characters.
Key points
- User input validation is critical to prevent incorrect calculations and invalid data
- The hasNextInt() method checks if the next Scanner input is a valid integer, returning true or false
- Use conditional statements to verify that values fall within acceptable ranges (e.g., age between 0 and 100)
- Display clear error messages when validation fails (e.g., 'Birth year is invalid')
- Chain validation conditions with if/else blocks to handle multiple types of invalid input
- Test your validation logic with edge cases like negative numbers and non-numeric characters
FAQ
What does the hasNextInt() method do?
It is a Scanner method that checks whether the next input from the user is a valid integer. It returns true if the input is an integer and false if it is something else like letters or symbols.
Why should we validate the birth year between 0 and 100?
This validation prevents unrealistic values (such as negative numbers) from being accepted, which would lead to incorrect age calculations and invalid results displayed to the user.
How do we handle cases where a user enters text instead of a number?
We use the hasNextInt() method to verify the input is an integer. If it returns false, we display an error message like 'Unable to analyze the birth year' and prevent the calculation from proceeding.