Search code examples
javaappletjapplet

How would I reduce the repetitiveness of this method?


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!


Solution

  • 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.