2014-04-09 120 views
0

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

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

     } 
+0

您应该检查堆栈跟踪并在程序中找到它发生的位置,并查看是否应该修改try-catch以包含更多代码或添加其他try-catch块。 –

回答

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()下一次调用将失败不管什么。

+0

谢谢,这非常有帮助!实际上,我把它放在另一个while循环之前。第二个循环是另一个数据验证,以确保它们不会选择列表之外的整数。 – user3516779