如何减少此方法的重复性?

时间:2014-11-26 03:22:27

标签: java applet japplet

这是我正在处理的代码(它是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() 

我如何减少if语句的重复性,因为我总共有5个,因为可以选择不同的操作量?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用switch语句。

switch(choice) {
case 1:
//code for if the choice 1
break;
case 2:
//code for if the choice is 2
break;

//do this for the rest of your choices

}

交换机基本上是一堆if和else if语句。

请记住添加一个break语句,如果你不这样做,它会一直执行,直到达到一个。 (称为"通过")

答案 1 :(得分:1)

之前询问数字并在之后给出结果:

//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