gpt4 book ai didi

java - 如何减少该方法的重复性?

转载 作者:行者123 更新时间:2023-12-02 05:13:40 24 4
gpt4 key购买 nike

这是我正在处理的代码(它是 CalculatorTester 类的一部分,是 Calculator 类的扩展):

 if (choice == 1) //Addition
{
System.out.println("Math Operation: Addition.");
System.out.println("Enter First Number.");
int a = in.nextInt();
System.out.println("Enter Second Number.");
int b = in.nextInt();
int endValue = c1.addition(a, b);
System.out.println("The Sum is: " + endValue + ".");
}
else if (choice == 2)
{
...More Code Here...
}//end of if()

Calculator对象内部的加法方法:

   public int addition(int a, int b)
{
endValue = a + b;
return endValue;
}//end of method addition()

由于可以选择的不同操作数量众多,我总共有 5 个 if 语句,因此我该如何减少 if 语句的重复性?

谢谢!

最佳答案

先询问数字,后给出结果:

//user selects operation
System.out.println("Enter First Number.");
int a = in.nextInt();
System.out.println("Enter Second Number.");
int b = in.nextInt();

int endValue;
if (choice == 1) //Addition
endValue = c1.addition(a, b);
else if (choice == 2)
endValue = c1.subtraction(a, b);
else
//throw exception since there was no endValue calculated

System.out.println("The result is: " + endValue + ".");

您还可以使用 switch/case 代替 if/if else/else .

关于java - 如何减少该方法的重复性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140786/

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