Exercise 4.2 Adding onto our Calculator


Lab goals

In this exercise, you will add an additional calculation into theCalculatorclass that you began in Part 1. This part adds method overloading and return values to your class. The high-level goals for the exercise are listed below:

  • Provide an overloaded version of theDividemethod to perform integer division.
  • Return the result of each calculation from each method as a return value instead of setting the field like you did in the first exercise.
  • Update theMainmethod using theCalculatorto support the new division method and the return result value.

Below is sample output from the finished application - notice the new "I" option.

Steps


Here are step-by-step instructions for completing this exericise. You can also utilize the high-level goals defined above to work through the code, relying on the below instructions to fill in any necessary details.

Implement method overloading in theCalculatorclass

In this section, you will build on the previous Calculator application by creating a method with the same name but different paraments inside theCalculatorclass.

  1. You can continue on from your previous exercise, or open the starter Calculator.sln contained in the Lab 02 Resources folder.
  2. Open the Calculator.cs source file and add a new version of theDividemethod that takes two integers as parameters and returns nothing (void).
    • Use the nameDivide, even though the class already has a method with that name. Since this method has different parameter types, it will be considered unique in the class. This is an example of method overloading.
    • Use the the modulo division (%) operator to get a remainder and assign it to theAnswerfield. Make sure to include the same test for zero that you did in the otherDividemethod!
  3. Build the program (Build > Build All) to make sure you don't have any compile errors.
    public void Divide(int number1, int number2)
    {
       if (number2 == 0) {
           Answer = 0;
       } else {
           Answer = number1 % number2;
       }
    }
    
  4. Open the Program.cs file and modify the code to call the newDivide
    method when you use the "I" key. This requires three changes:

    • Add "I" into theConsole.Writeprompt around line 17.
    • Add in a newcaseinto theswitchblock which calls the newDividemethod. This will require that you cast your two input numbers to integers - here's the code you need to add:
      case 'I':
          calc.Divide((int)first, (int)second);
          break;
      
    • Add the "I" into the errorConsole.WriteLinewhen no valid input is detected in thedefault
      case.

      public static void Main ( string[] args )
      {
          Console.Write( "First number? " );
          float first = float.Parse( Console.ReadLine( ) );
          Console.Write( "Second number? " );
          float second = float.Parse( Console.ReadLine( ) );
      
          Calculator calc = new Calculator();
      
          while ( true ) {
              Console.Write( "A)dd S)ubtract M)ultiply D)ivide, I)nteger division, Q)uit: " );
              var operation = Console.ReadLine( ).ToUpper( )[0];
      
              if ( operation == 'Q' )
                  break;
      
              switch ( operation ) {
                  case 'A':
                      calc.Add(first, second);
                      break;
                  case 'S':
                      calc.Subtract(first, second);
                      break;
                  case 'M':
                      calc.Multiply(first, second);
                      break;
                  case 'D':
                      calc.Divide(first, second);
                      break;
                  case 'I':
                      calc.Divide((int)first, (int)second);
                      break;
                  default:
                      Console.WriteLine( "Please enter A, S, M, D, I or Q" );
                      break;
              } 
              Console.WriteLine("Your answer is {0}", calc.Answer);
          } 
      }
      

    5.Build and run the application to try out your new integer division support!

Use thereturnkeyword to return values from methods

One problem we have right now is that we are only returning the remainder from our integer division method. It would be helpful to return both the quotient and the remainder. We could do this by setting up another field, or we could use thereturnkeyword to return a value directly from ourDividemethod. Let's take this approach now.

  1. Open the Calculator.cs file and locate your integerDividemethod you added.
  2. Change the method signature to return anininstead ofvoid.
  3. Modify the code to set theAnswerfield to the normal division result (/) and return the remainder (%) result.

    public int Divide(int number1, int number2)
    {
        if (number2 == 0) {
            Answer = 0;
            return 0;
        }
    
        Answer = number1 / number2;
        return number1 % number2;
    }
    
  4. Next, open the Program.cs file again and modify it to use both the return value and theAnswerfield with the following steps:

    • Add a new variable, named remainder in the Main method to hold the remainder result - initialize it to zero since it's only assigned with the new Divide method. This should be locatedinside the while loop so it gets assigned to zero each time.

    • Assign the new field to the return value from your integerDivide method.

    • Add anif-else condition around yourConsole.WriteLine output to print the remainder along with the answer if the new remainder field is non-zero. Here's an example of the Console.WriteLineto use:

    Console.WriteLine("Your answer is {0} with a remainder of {1}", 
                      calc.Answer, remainder);
    
    public static void Main ( string[] args )
    {
        Console.Write( "First number? " );
        float first = float.Parse( Console.ReadLine( ) );
        Console.Write( "Second number? " );
        float second = float.Parse( Console.ReadLine( ) );
    
        Calculator calc = new Calculator();
    
        while ( true ) {
            Console.Write( "A)dd S)ubtract M)ultiply D)ivide, I)nteger division, Q)uit: " );
            var operation = Console.ReadLine( ).ToUpper( )[0];
    
            if ( operation == 'Q' )
                break;
    
            int remainder = 0;
    
            switch ( operation ) {
                case 'A':
                    calc.Add(first, second);
                    break;
                case 'S':
                    calc.Subtract(first, second);
                    break;
                case 'M':
                    calc.Multiply(first, second);
                    break;
                case 'D':
                    calc.Divide(first, second);
                    break;
                case 'I':
                    remainder = calc.Divide((int)first, (int)second);
                    break;
                default:
                    Console.WriteLine( "Please enter A, S, M, D, I or Q" );
                    break;
            } 
    
            if (remainder != 0) {
                Console.WriteLine("Your answer is {0} with a remainder of {1}", calc.Answer, remainder);
    
            } else {
                Console.WriteLine("Your answer is {0}", calc.Answer);
            }
        } 
    }
    
  5. Build and run your program to see the final results:

results matching ""

    No results matching ""