2017-04-06 50 views
1

我想驗證用戶在菜單上的輸入。選項是1,2,3和4.我試圖在輸入一個字母時處理InputMismatchException錯誤。我看不出我做錯了什麼使我的代碼陷入無限循環。我的異常處理中的無限循環?

System.out.println("What will be your starting balance?"); 

    double startingBalance =0; 
    boolean check = false; 
    while(!check) { 
     try { 
      startingBalance = input.nextDouble(); 
      check = true; 
     } 
     catch (InputMismatchException e) { 
      System.out.println("Invalid input!"); 
      //startingBalance = 0; 
      //e.printStackTrace(); 
      //check = false; 
     } 
    } 

它看起來像進入捕獲部分,但重複循環,而不是回到嘗試。我試過input.nextDouble();

來清除輸入緩衝區,但什麼都沒做。任何幫助將不勝感激。

回答

0

您可以使用input.nextLine();清除您的掃描儀在你的catch塊:

while (!check) { 
    try { 
     startingBalance = input.nextDouble(); 
     check = true; 
    } catch (InputMismatchException e) { 
     System.out.println("Invalid input!"); 
     input.nextLine();//this will clear your Scanner and repeat again 
    } 
} 

我可以問你爲什麼使用nextLine(),而不是nextDouble()?

因爲nextLine移動掃描儀到下一行

+0

啊,那固定我的問題。非常感謝! –

+0

我可以問爲什麼你使用nextLine()而不是nextDouble()? –

+0

我明白。感謝clairifying!我會驗證它。我需要等10分鐘才能完成。 –

0

你需要設定布爾檢查=第一次檢查後假,還可以使用input.nestLine()