gpt4 book ai didi

java - 将重复的 if-else 语句修改为更清晰的代码

转载 作者:行者123 更新时间:2023-11-30 06:04:00 25 4
gpt4 key购买 nike

我正在制作一个计算器 Gui。有什么方法可以使这段代码看起来更干净而不重复行。

double num1, num2, ans, doub;
num1 = Double.parseDouble(FirstInput.getText());
num2 = Double.parseDouble(SecondInput.getText());
oper = (Operator.getText());

if(oper.equals("+")){
ans = num1 + num2;
doub = Math.round(ans * 100000.0) / 100000.0;
if(doub == (int) ans){
Answer.setText(Integer.toString((int) ans));
} else{
Answer.setText(Double.toString(doub));
}
}
if(oper.equals("-")){
ans = num1 - num2;
doub = Math.round(ans * 100000.0) / 100000.0;
if(doub == (int) ans){
Answer.setText(Integer.toString((int) ans));
} else{
Answer.setText(Double.toString(doub));
}
}
if(oper.equals("/")){
ans = num1 / num2;
doub = Math.round(ans * 100000.0) / 100000.0;
if(doub == (int) ans){
Answer.setText(Integer.toString((int) ans));
} else{
Answer.setText(Double.toString(doub));
}
}
if(oper.equals("x")){
ans = num1 * num2;
doub = Math.round(ans * 100000.0) / 100000.0;
if(doub == (int) ans){
Answer.setText(Integer.toString((int) ans));
} else{
Answer.setText(Double.toString(doub));
}
}

最佳答案

使用 java-8,您可以通过引入接受数字和 DoubleBinaryOperator 的新方法来使其变得非常奇特:

public void setAnswerText(double num1, double num2, DoubleBinaryOperator operator){
final double ans = operator.applyAsDouble(num1, num2);
final double doub = Math.round(ans * 100000.0) / 100000.0;
if(doub == (int) ans){
Answer.setText(Integer.toString((int) ans));
} else{
Answer.setText(Double.toString(doub));
}
}

并使用 switch 语句:

final double num1 = Double.parseDouble(FirstInput.getText());
final double num2 = Double.parseDouble(SecondInput.getText());
final String oper = (Operator.getText());
final DoubleBinaryOperator operator;
switch(oper){
case "+":
operator = (a, b) -> a+b;
break;
case "-":
operator = (a, b) -> a-b;
break;
case "/":
operator = (a, b) -> a/b;
break;
case "x":
operator = (a, b) -> a*b;
break;
default:
throw new UnsupportedOperationException();
}

setAnswerText(num1, num2, operator);

这样,您就可以在 switch 语句中找到匹配的运算符,然后使用数字和找到的运算符执行该方法

关于java - 将重复的 if-else 语句修改为更清晰的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854473/

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