Your basic ‘read until you get an integer’ block should look like this:
do {
try {
year = scan.nextInt();
if (year <= 0) { // see comment
System.out.println("ERROR. Please enter positive number");
}
} catch(Exception e){
System.out.println("ERROR. Please enter a number "
+ "without decimals");
scan.next();
year = -1;
}
} while (year <= 0);
So if there’s non-numeric input, you actively set a value that will cause you to loop, rather than relying on what might have been there already.
Also, you want to make sure the input was positive.
Given that you should be able to figure out the entire program.
Where I said “see comment”, perhaps you might want to check for a reasonable year; maybe throw out anything before about 1752 (when Britain and the US adopted the Gregorian calendar).
Your original problem likely was due to the year % 1 != 0
condition. That means “remainder when dividing year by 1 is not 0”. It’s always true for non-negative values. I’d have to look up how Java implements %
for negative values to answer in that case.
CLICK HERE to find out more related problems solutions.