Java输入不匹配异常处理

时间:2014-04-09 19:42:11

标签: java exception-handling try-catch

我正在处理我正在为课程编写的库存管理程序处理输入输出异常处理的问题。我现在正在选择的选项是添加一个客户。首先,他们根据客户是批发还是零售来选择1或2。如果他们意外输入非int值,我想阻止程序爆炸。尽管我的try-catch,我仍然会收到输入不匹配的异常。这是我现在的代码。

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

        }

1 个答案:

答案 0 :(得分:0)

你应该在循环中移动try / catch:

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

异常处理程序中的scan.next()将会输入他们输入的任何无效输入,否则无论如何,您对nextInt()的下一次调用都将失败。