DEV Community

websplee
websplee

Posted on

Implementing Standard Calculator

I was recently challenged to develop a standard basic calculator that would evaluate a given expression following the BODMAS rules and of course, return the answer. The one rule to this was that I did not have to use any inbuilt evaluation methods.

So lets get started. I began with an interface that defined the methods I was going to use.

interface IBaseCalculator
{
string EvaluateEquation(string equation);
string EvaluateOperation(string equation, char op);
double EvaluateAddition(double a, double b);
double EvaluateSubtraction(double a, double b);
double EvaluateMultiplication(double a, double b);
double EvaluateDivision(double a, double b);
}

I then went ahead and implemented this with a constructor taking in the set of operations that I needed to support. In this case division, multiplication, addition and subtraction. This is the interesting part. I created an array of characters to represent the operations allowed for this calculator.

NOW, in order to make sure the rules of BODMAS were adhered to, I had to declare the array in the order representing BODMAS rule.

The EvaluateOperation method iterates through the equation and starts breaking it down following the BODMAS rules. It does this by invoking the appropriate Evaluate method. In case of multiplication, it calls EvaluateMultiplication.

public string EvaluateOperation(string equation, char op)
{
int i = 0;

        if (equation.Contains(op))
            i = equation.IndexOf(op);
        switch (op)
        {
            case '(':
                throw new NotImplementedException();
            case ')':
                throw new NotImplementedException();
            case '/':
                answer = EvaluateDivision(Double.Parse(equation[i - 1].ToString()),
                         Double.Parse(equation[i + 1].ToString()));
                break;
            case '*':
                answer = EvaluateMultiplication(Double.Parse(equation[i - 1].ToString()),
                         Double.Parse(equation[i + 1].ToString()));
                break;
            case '+':
                answer = EvaluateAddition(Double.Parse(equation[i - 1].ToString()),
                         Double.Parse(equation[i + 1].ToString()));
                break;
            case '-':
                answer = EvaluateSubtraction(Double.Parse(equation[i - 1].ToString()),
                         Double.Parse(equation[i + 1].ToString()));
                break;
        }

Please go ahead and play with the solution located here
https://github.com/websplee/StandardCalculator/blob/master/StandardCalculator/BaseCalculator.cs

Top comments (0)