Search code examples
javaexceptionwhile-looptry-catchinputmismatchexception

Exception Handling in a while loop


The problem I am having with this code is the following: the variable number can't be a String so I tried to use a try, catch (InputMissmatchException) statement to take care of the issue. However, when in goes in the loop and someone enters a String, the exception is handle but it goes through the loop again using the last valid entry. i.e. I enter 5 and then I enter "hello" the result is: "You must enter a number." but now 5 is counted again.

This makes the counter add one too many to the count variable. And if the user keep using a String, the loop keep adding the last valid entry over and over so the count would be wrong at the end.

Logically speaking I want the program to handle the issue and ask the user to enter a correct entry until an acceptable integer is enter without going through the while loop again; and when the user enters a valid entry, to keep looping or exist (-1).

int number = 0;
int[] count = new int[11];

    try
        {
        number = input.nextInt(); 
        } 
        catch (InputMismatchException y)
        {
        System.out.println("You must enter a number.");
        input.nextLine();

        }    


    while (number != -1)
    {
        try 
        {
            ++count[number];
        } 
        catch (IndexOutOfBoundsException e) 
        {
            System.out.println("Please enter a valid number from the menu.");
        }

        try
        {
        number = input.nextInt();
        } 
        catch (InputMismatchException y)
        {
        System.out.println("You must enter a number.");
        input.nextLine();

        } 
    }

Solution

  • Sounds like you want a while loop until they enter a number

    int number = 0;
    int[] count = new int[11];
    
    while(true) {
        try
        {
        number = input.nextInt();
        break;
        } 
        catch (InputMismatchException y)
        {
        System.out.println("You must enter a number.");
        input.nextLine();
    
        }  
    }  
    
    
    while (number != -1)
    {
        try 
        {
            ++count[number];
        } 
        catch (IndexOutOfBoundsException e) 
        {
            System.out.println("Please enter a valid number from the menu.");
        }
    
        while(true) {
            try
            {
                number = input.nextInt();
                break;
            } 
            catch (InputMismatchException y)
            {
                System.out.println("You must enter a number.");
                input.nextLine();
            } 
        }
    
    }