Question

I am having issues dealing with input output exception handling on an Inventory Management program I am writing for class. The option I am working on right now is to add a customer. First they select a 1 or a 2 based on whether the customer is wholesale or retail. I want to stop the program from blowing up if they accidentally enter a non-int value. I keep getting an input mismatch exception despite my try-catch Here is my code right now.

        int i = 0;


        try
        {
        System.out.println("Please indicate if customer is wholesale or retail.  Type 1 for wholesale or 2 for retail");
        i = scan.nextInt();
        }



        catch (InputMismatchException e) 
        {
        System.out.println("You did not input a valid value.  Please enter an Integer value between 1 and 2");


        }


        while (i<1 || i>2)
        {
            System.out.println("You did not enter a valid value.  Please enter an integer between 1 and 2");
            i = scan.nextInt();
        }


    //  The data validation previously provided was not running correctly so I changed the logic around


        if (i == 2)
        {
            next.setType("Retail");
            System.out.println("The customer is Retail");
            System.out.println("");

        }
        else if (i == 1)
        {
            next.setType("Wholesale");
            System.out.println("The customer is Wholesale");
            System.out.println("");

        }
Was it helpful?

Solution

You should move the try/catch inside the loop:

int i = 0;

while (i < 1 || i > 2)
{
    try
    {
        System.out.println("Please indicate if customer is wholesale or retail.  Type 1 for wholesale or 2 for retail");
        i = scan.nextInt();
    } 
    catch (InputMismatchException e) 
    {
        System.out.println("You did not input a valid value.  Please enter an Integer value between 1 and 2");
        scan.next();
    }
}
...

The scan.next() in the exception handler will eat whatever invalid input they entered, otherwise your next call to nextInt() will fail no matter what.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top