Project design
Design the structure of the calculator project and write the skeleton code.
Project: Calculator
In this 5-lesson project you'll build a calculator. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use what you learned before:
- defining a class with
class doublevariables and parameters- declaring and calling methods
- writing output with
Console.WriteLine
You'll also learn user input, switch menu, while loop and try/catch error handling. Ready? Let's start.
Calculator class skeleton
The Calculator class has four methods: Add, Subtract, Multiply, Divide. Each method takes two double parameters and returns a double. In this first lesson you'll write a skeleton with empty bodies that return 0;
class Calculator
{
public double Add(double a, double b)
{
return 0;
}
}In later lessons you'll fill these methods with real arithmetic. For now, just building the class skeleton is enough.
Exercise Write the Calculator class skeleton
Define the empty-bodied Calculator class. Four methods (Add, Subtract, Multiply, Divide) each take two double parameters and return 0; Add the class before class Program.
Show example solution
Add the Calculator class and four methods.
Example solution:
using System;
class Calculator
{
public double Add(double a, double b)
{
return 0;
}
public double Subtract(double a, double b)
{
return 0;
}
public double Multiply(double a, double b)
{
return 0;
}
public double Divide(double a, double b)
{
return 0;
}
}
class Program
{
static void Main()
{
var calc = new Calculator();
Console.WriteLine(calc.Add(3, 4));
}
}
Test yourself
-
Why design the calculator as a class?
- To keep code organized and together
- To make the program run slower
- Because we must write fewer lines
- Because C# won't compile without a class
Show answer
To keep code organized and together — Correct; a class keeps related methods together and organizes code.
-
Write the addition method name
public double ____(double a, double b) { return 0; }Show answer
public double Add(double a, double b) { return 0; } -
Match each method to its operation
- Add
- Addition
- Subtract
- Subtraction
- Multiply
- Multiplication
- Divide
- Division