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);
答案 0 :(得分: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);
答案 1 :(得分:2)
首次输入有效高度后,循环将按预期工作。但是,如果您第一次输入无效高度,则会抛出NFE并且您的有效指示符为false。所以它会再次迭代它,因为你不再读高度,你将最终进入无限循环(它将一次又一次地遵循上述步骤)。
所以你需要在循环中移动JOptionPane.showInputDialog
部分。试试这段代码。
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);