Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping do...while uncertainty

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());
like image 516
user3397080 Avatar asked Dec 19 '22 17:12

user3397080


2 Answers

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:

  • If a user fill a correct number month will be filled.
  • Otherwise, Exception will be thrown and 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().

like image 184
Orel Eraki Avatar answered Feb 03 '23 11:02

Orel Eraki


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());
like image 34
Sergey Kalinichenko Avatar answered Feb 03 '23 11:02

Sergey Kalinichenko