How would I reduce the repetitiveness of this method?

72 Views Asked by At

Here is the code I am working on(Its part of the CalculatorTester Class which is an extension of the Calculator Class):

 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() 

The addition method inside the Calculator object:

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

How would I reduce the Repetitiveness of the if Statements, as I have 5 in total due to the amount of different operations one can choose from?

Thanks!

2

There are 2 best solutions below

1
On BEST ANSWER

Ask for numbers before and give results after:

//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 + "."); 

You can also use a switch/case instead of if/if else/else.

0
On

Use a switch statement.

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

}

A switch is basically a bunch of if and else if statements.

Remember to add a break statement, if you don't, it keeps executing until it reaches one. (called "falling through")