2014-04-09 79 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