我尝试将两个循环合并到一个do循环中,但每次输入无效值时,它都不会提示我错误消息并要求再次输入值。相反,它只是转到下一个提示语句。
do {
try {
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
}
if (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS) {
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
}
} while (dependents < MIN_DEPENDENTS || dependents > MAX_DEPENDENTS);
do {
try {
income = Double.parseDouble(JOptionPane.showInputDialog("amount of income:"));
}
catch (NumberFormatException e) {
income = MIN_INCOME - 1;
}
if (income < MIN_INCOME || income > MAX_INCOME) {
JOptionPane.showMessageDialog(null, "income must be between $0 and $999,999.");
}
} while (income < MIN_INCOME || income > MAX_INCOME);
答案 0 :(得分:2)
不,但您可以创建某种GetInput函数并传入min,max,promptText和errorText。这样可以避免重复代码。
dependents = getInput(MIN_DEPENDENTS, MAX_DEPENDENTS,"number of dependents:","Number of dependents must be between 0 and 9.")
income = getInput(MIN_INCOME,MAX_INCOME,"amount of income:","income must be between $0 and $999,999.")
private double getInput(double min, double max, String promptText, String errorText) {
double result = 0.0;
do {
try {
result = Double.parseDouble(JOptionPane.showInputDialog(promptText));
}
catch (NumberFormatException e) {
result = min - 1;
}
if (result < min || result > max) {
JOptionPane.showMessageDialog(null, errorText);
}
} while (result < min || result > max);
return result;
}
答案 1 :(得分:0)
Dan,你需要在你的catch区块下面加上显示错误信息并再次提示输入。
catch (NumberFormatException e) {
dependents = MIN_DEPENDENTS - 1;
JOptionPane.showMessageDialog(null, "Number of dependents must be between 0 and 9.");
dependents = Integer.parseInt(JOptionPane.showInputDialog("number of dependents:"));
}
答案 2 :(得分:0)
另一个选项可以是数组中的主要输入列表,然后在while循环中使用它
Object[][] input = {
{"number of dependents", MIN_DEPENDENTS, MAX_DEPENDENTS},
{"amount of income", MIN_INCOME, MAX_INCOME},
};
int index = 0;
int value, min, max;
do {
Object[] inputDetails = input[index];
String label = inputDetails[0].toString();
min = Integer.valueOf(inputDetails[1].toString());
max = Integer.valueOf(inputDetails[2].toString());
try {
value = Integer.parseInt(JOptionPane.showInputDialog(label));
} catch (NumberFormatException e) {
value = min - 1;
}
if (value < min || value > max) {
JOptionPane.showMessageDialog(null, String.format("%s must be between %s and %s", label, min, max));
} else {
index++;
}
} while ((value < min || value > max) || index < input.length);