Search code examples
javainfinite-loopdo-whileinputmismatchexception

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());

Solution

  • 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().