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
A
回答
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);
相關問題
- 1. 爲什麼我在python中獲得raw_input的無限循環?
- 2. 爲什麼Java toString()會在間接循環中無限循環?
- 3. 爲什麼我用pg_search獲得無限循環?
- 4. 爲什麼我的while循環無限?
- 5. 爲什麼我的循環無限
- 6. python中的無限循環 - 爲什麼?
- 7. 爲什麼會無限循環? (Java)
- 8. 爲什麼我在我的ifstream中有一個無限循環?
- 9. 無限循環。爲什麼?
- 10. 無限循環 - 爲什麼?
- 11. 爲什麼我陷入無限循環
- 12. 爲什麼我的程序中存在無限循環?
- 13. 爲什麼我的循環在遞歸函數中無限?
- 14. 爲什麼這個while循環卡在無限循環中?
- 15. 無限循環在Java中
- 16. 爲什麼我的java代碼進入無限循環?
- 17. Java。爲什麼我的代碼返回無限循環?
- 18. 爲什麼這是java中的無限循環?
- 19. 爲什麼我一直在無限循環中結束?
- 20. 爲什麼我會變得無限循環?
- 21. 爲什麼我得到一個無限循環?
- 22. 爲什麼我得到一個無限循環?
- 23. C++,獲得無限循環
- 24. Java中的無限循環
- 25. 我無法弄清楚爲什麼我得到一個無限循環在Python
- 26. 爲什麼字符串中的空格使得我的代碼無限循環?
- 27. 爲什麼我的代碼中有無限循環?
- 28. 什麼導致我的無限循環?
- 29. 爲什麼scanf在無效輸入中陷入無限循環?
- 30. 爲什麼我無法獲得車把來循環?
'iHeight'總是生產NFE。您在循環迭代中使用相同的值。我相信你不想這樣做。 – SacJn
可能是因爲'iHeight'值在循環內從不改變。 – Titus
如果從parseDouble拋出異常,則不會執行'valid = true'行。結果取決於iHeight中的內容:如果iHeight毫無例外地被解析,那麼您將不會加載無限循環,否則......無限循環。 :) – Willmore