From the javadoc, nextInt
throws "InputMismatchException
- if the next token does not match the Integer regular expression, or is out of range". This means that you cannot blindly call nextInt
and hope that the input will be an int
.
You probably should read the input as a String
and perform checks on that input so see whether it is valid.
public static void main(String[] args) throws IOException {
final Scanner scanner = new Scanner(System.in);
//read year
final String yearString = scanner.next();
final int year;
try {
year = Integer.parseInt(yearString);
//example check, pick appropriate bounds
if(year < 2000 || year > 3000) throw new NumberFormatException("Year not in valid range");
} catch (NumberFormatException ex) {
throw new RuntimeException("Failed to parse year.", ex);
}
final String monthString = scanner.next();
final int month;
try {
month = Integer.parseInt(monthString);
//example check, pick appropriate bounds
if(month < 1 || month > 12) throw new NumberFormatException("Month not in valid range");
} catch (NumberFormatException ex) {
throw new RuntimeException("Failed to parse month.", ex);
}
//and the rest of the values
}
Then, when you have all the inputs and they are known to be valid, then call setWhen
.
Obviously you can, instead of throwing an exception, try and read the number again.