In the catch block, I'm trying to correct for user bad-input issues. When testing it, if I use the "break" keyword, it doesn't jump to the initial question. If I use "continue", it loops infinitely. "Sc.next();" doesn't seem to resolve it either.
Here's the relevant part of the code.
public class ComputerAge {
private static int age;
private static int year;
private static int month;
private static int date;
private static Calendar birthdate;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the numeral representing your birth month: ");
do {
try {
month = sc.nextInt();
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
break;
}
} while (!sc.hasNextInt());
In order to fix the problem, we should identify what we want to accomplish at the end.
We want the month to be a numeral month, that is number > 0.
Thus:
month
will be filled.month
will stay as '0'.Conclusion: We want our program will keep running when month is equals 0.
The solution is pretty simple:
While condition should be:
while (month == 0);
And you should change break
to sc.next()
.
The problem with your approach is that when you call sc.nextInt()
and it throws an exception, Scanner
does not advance its reading position. You need to advance the reading pointer by calling sc.next()
inside the catch
block instead of the break
:
do {
try {
month = sc.nextInt();
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
sc.next(); // This will advance the reading position
}
} while (!sc.hasNextInt());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With