gpt4 book ai didi

java - 是否可以合并这两个 do 循环

转载 作者:行者123 更新时间:2023-12-02 04:34:17 25 4
gpt4 key购买 nike

我尝试将两个循环合并为一个 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);

最佳答案

不,但您可以创建某种 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;
}

关于java - 是否可以合并这两个 do 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com