2015-09-01 37 views
-1
iHeight = JOptionPane.showInputDialog(null, "What is your height in inches?"); 
boolean valid = false; 
do { 
    try { 
     cHeight = Double.parseDouble(iHeight); 
     valid = true; 
    } catch (NumberFormatException e) { 
     JOptionPane.showMessageDialog(null, "Invalid number, \nplease re-enter your height"); 
    }   
} while(! valid); 
+1

'iHeight'總是生產NFE。您在循環迭代中使用相同的值。我相信你不想這樣做。 – SacJn

+5

可能是因爲'iHeight'值在循環內從不改變。 – Titus

+0

如果從parseDouble拋出異常,則不會執行'valid = true'行。結果取決於iHeight中的內容:如果iHeight毫無例外地被解析,那麼您將不會加載無限循環,否則......無限循環。 :) – Willmore

回答

4

我們假設Double.parseDouble(iHeight)確實會拋出一個NumberFormatException並且您可以捕獲它。由於在設置valid = true之前拋出異常,所以有效值永遠不會更改,因此您將繼續循環。現在因爲你的循環永遠不會改變iHeight的值,所以每次迭代循環時都會拋出同樣的異常,所以最終會出現無限循環。解決這個問題

一種方式是讓用戶輸入自己的身高循環,給他們一個機會,以解決他們的無效輸入,如果有異常拋出:

//you've already declared the variables iHeight and cHeight somewhere above here 
boolean valid = false; 
do { 
    iHeight = JOptionPane.showInputDialog(null, "What is your height in inches?"); 

    try { 
     cHeight = Double.parseDouble(iHeight); 
     valid = true; 

    } catch (NumberFormatException e) { 
     JOptionPane.showMessageDialog(null, "Invalid number, \nplease re-enter your height"); 
    }   
} while(!valid); 
2

第一次,如果你輸入有效高度,然後您的循環將按預期工作。但是,如果您第一次輸入無效高度,則會引發NFE,並且您的有效指標是錯誤的。所以它會再次迭代它,並且當你不再讀取高度時,你將以無限循環結束(它將一次又一次地執行上述步驟)。

因此,您需要將JOptionPane.showInputDialog部分移到while循環中。試試這個代碼。

boolean valid = false; 
do { 
    iHeight = JOptionPane.showInputDialog(null, "What is your height in inches?"); 
    try { 
     cHeight = Double.parseDouble(iHeight); 
     valid = true; 
    } catch (NumberFormatException e) { 
     valid = false; // This line is not necessary but you can add it to make it more readable. 
     JOptionPane.showMessageDialog(null, "Invalid number, \nplease re-enter your height"); 
    } 
} while(!valid);