2016-05-18 157 views
1

我面對java.util.InputMismatchException;inputmismatchexception:進入無限循環?

我趕上InputMismatchException時,但我不明白爲什麼它會進入無限循環以第一輸入錯誤後,輸出繼續這樣:

enter two integers 
exception caught 

這樣下去重複

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int flag = 0; 
    while (flag != 1) { 
     try { 
      System.out.println("enter two integers"); 
      int a = sc.nextInt(); 
      int b = sc.nextInt(); 
      int result = a + b; 
      flag = 1; 
      System.out.println("ans is" + result); 
     } catch (NumberFormatException e) { 
      System.out.println("exception caught"); 
     } catch (InputMismatchException e) { 
      System.out.println("exception caught"); 
     } 
    } 
} 

回答

0

如果按回車鍵,你需要消耗這個人物太

int a = sc.nextInt(); 
int b = sc.nextInt(); 
sc.nextLine(); 

,那麼你可以進入

2 3 <CR> 
+0

@Berger是啊,我不知道OP很希望如何進入他的數據。 –

0

在你的代碼,正趕上InputMisMatchException,你只是打印一條消息,這將導致再次將while循環。

 int a = sc.nextInt(); 
     int b = sc.nextInt(); 

當這些線扔你flag=1不會被設置例外,你會在一個無限循環。糾正您的異常處理,並打破循環或通過讀取字符串來清除掃描儀輸入。

0

您需要清除緩衝區,以便在拋出異常之後對緩衝區nextInt()無效。添加finally塊,並調用其內部sc.nextLine()

while (flag != 1) { 
    try { 
     System.out.println("enter two integers"); 
     int a = sc.nextInt(); 
     int b = sc.nextInt(); 
     int result = a + b; 
     flag = 1; 
     System.out.println("ans is" + result); 

    } catch (NumberFormatException e) { 
     System.out.println("exception caught"); 
    } catch (InputMismatchException e) { 
     System.out.println("exception caught"); 
    } finally { //Add this here 
     sc.nextLine(); 
    } 
} 

工作例如:https://ideone.com/57KtFw

+0

雖然這將適用於像'1 2'這樣的數據,但它會因爲'1 2 3'這樣的數據而失敗,因爲'nextLine()'被放置在'finally'中,這意味着即使不拋出異常也會消耗整行*所以它也會消耗'3',這可能是後期應用程序的有效輸入。最好是在catch塊中處理每個異常,'finally'部分是針對需要執行的強制任務,無論異常是否被拋出。 – Pshemo