Exercise 4.1 Building a Calculator


Lab goals

In this exercise you will define a newCalculatorclass with some simple methods to perform arithmetic operations. You will then use the class with an existing program that has been created for you to read two numeric values and a math operation from the console and print the result of the selected operation applied to the two values. The high-level goals for the exercise are listed below:

  1. Create aCalculatorclass.
  2. Define methods to perform addition, subtraction, multiplication and division on two floating point values.
  3. Modify the existingProgramclass which has been defined to create an instance (object) of yourCalculator.
  4. Call the appropriate math operation on theCalculator, passing it the two floating point values read from the console.
  5. Display the result of the operation by reading a field defined on theCalculatorclass.

Below is output from the finished application showing sample data from two differentCalculatorobjects.

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.

Open the starter project

  1. Locate the starter project contained in the Part 01 Resources/Start folder included with this exercise and open the Calculator.sln file using either Visual Studio or Visual Studio.
  2. Examine the Program.cs file which is already present in the project. Notice that it defines your main entry point (Main ) as a method in a class namedProgram. This is the place your program will begin execution. It currently performs the following steps:
    • Prompts the user, using theConsole, for two numbers.
    • Enters an infinite (never-ending)whileloop which reads an operation to add, subtract, multiply, divide or 'Q' for quit.
    • Has anifstatement to check for 'Q' to exit the loop using abreakstatement (remember, this terminates the loop or switch statement being executed).
    • Uses aswitchstatement to evaluate the first letter of the input (upper-cased), with placeholder comments for where you will use yourCalculatorclass.
    • Has a placeholder comment to output the result of the operation.
  3. Identify all the // TODO: comments in the code - this is where you will make your changes to this class. Make sure you understand the basic operation of this program before continuing - ask the instructor for clarification if there is something you do not understand.

Create aCalculatorclass

In this section, you will define a class namedCalculatorwhich will be used to perform mathmatical operations (Add, Subtract, Multiply and Divide).

  1. The first step is to add a new class file into the project. You can just add a simple text file with the proper extension (.cs), however a better way is to let the IDE know what you want to add through the New File dialog which displays a set of common file types to create. You access this dialog using the File > New >File menu option.

  2. In the New File dialog, choose the Empty Class entry from the General category, enter Calculator as the Name, then click the New button (see below). Visual Studio will generate an empty file named Calculator.cs for you.

  3. Examine the code which has been created for you. You should have a new public class named Calculator
    in the project namespace (which is also Calculator - this was defined when we created the initial project and matches the name of the project itself). The code should look something like:

    using System;
    
    namespace Calculator
    {
        public class Calculator
        {
            public Calculator()
            {
            }
        }
    }
    
  4. There is one part you may not recognize - that's the odd-looking method defined in the class:

    public class Calculator
    {
         public Calculator()
         {
         }
    }
    

    This is a special method called a _constructor _which can be used to perform initialization when an instance of the class is created. We are going to talk about these in a future module and we don't need this, so you can delete the definition from your code (the highlighted bits above).

Define methods to perform arithmetic operations

Next, let's define some public methods on the calculator class to perform simple arithmetic calculations on two floating point numbers. We want to have methods to Add, Subtract, Multiply and Divide

  1. Let's start with Add. Go ahead and define a method namedAddthat takes twofloatparameters, you can name them whatever you like, and returns nothing (hint:void)

    ...
    
    public class Calculator
    {
        public void Add(float number1, float number2)
        {
        }
    }
    
  2. Next, let's provide some code for the method - go ahead and create a public field named Answer of typefloatin the class to hold our calculation result, place this code into the _class _portion, not into theAddmethod.

    ...
    
    public class Calculator
    {
        public float Answer;
    
        public void Add(float number1, float number2)
        {
        }
    }
    
  3. Finally, assign theAnswerfield to the added value of your two numbers, remember we use the + symbol to add things in C#.

    ...
    
    public class Calculator
    {
        public float Answer;
    
        public void Add(float number1, float number2)
        {
            Answer = number1 + number2;
        }
    }
    
  4. Build the application (Build > Build All (or Solution) on the menu) to make sure it compiles correctly, correct any errors that are reported by comparing your code against the above example.

  5. Now, complete the other three operators in the same way using three methods:Subtract,MultiplyandDivide.

    • All three methods should take twofloatparameters and returnvoid.
    • Assign the result of the operation to theAnswerfield.
    • For an extra challenge, theDividemethod should make sure the second number (the divisor) is not zero using anifstatement, if you find a zero, set theAnswerfield to-1 to indicate an error.
      You can check your code against the below example if you'd like a little help.

      ...
      
      public class Calculator
      {
          public float Answer;
      
          public void Add(float number1, float number2)
          {
              Answer = number1 + number2;
          }
      
          public void Subtract(float number1, float number2)
          {
              Answer = number1 - number2;
          }
      
          public void Multiply(float number1, float number2)
          {
              Answer = number1 * number2;
          }
      
          public void Divide(float number1, float number2)
          {
              if (number2 == 0) {
                  Answer = -1;
              } else {
                  Answer = number1 / number2;
              }
          }
      }
      
    • Make sure to build the application before moving to the next step (Build > Build All (or Solution) on the menu) to make sure it compiles correctly, correct any errors that are reported by comparing your code against the above example.

Modify the existingProgramclass to use theCalculator

Now it's time to use our newCalculatorclass. Let's modify the suppliedMainmethod defined in theProgramclass.

  1. Open the Program.cs file (double-click on the file in the Solution Explorer).
  2. Recall the // TODO: comments you looked at earlier - using these as a guide, perform the steps indicated:
    • Create aCalculatorobject usingnew.
    • Perform each operation (add, subtract, multiply and divide) using theCalculatorobject.
    • Output the result (Answer) field from theCalculatorusingConsole.WriteLine. Remember, we use _placeholders _to indicate where we want parameters to be inserted, so you could use the string"Your answer is {0}"to reproduce the output shown in the initial screen shot at the start of the exercise. Make sure to pass theAnswerfield!
using System;

namespace Calculator
{
    public class Program
    {
        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 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;
                    default:
                        Console.WriteLine( "Please enter A, S, M, D or Q" );
                        break;
                } 
                Console.WriteLine("Your answer is {0}", calc.Answer);
            } 
        }
    }
}

results matching ""

    No results matching ""