作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我正在处理的代码(它是 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/
我正在尝试使用重复包装脚本(duplicity-restore.sh)恢复文件,内容如下: #!/bin/bash # Export some ENV variables so you don't h
在过去的几周里,我们的 mysql 数据库一直在随机崩溃。 - 我已经检查了所有数据库是否损坏,但一切正常。 编辑 2016.01.14 - 经常弹出的错误如下 - InnoDB: Database
我是一名优秀的程序员,十分优秀!