Answer to Question #216963 in C# for Question 03

Question #216963

Create a class Calculator having two integer data members and one string member i.e. operator. Class contains only one customized constructor which takes two arguments, set the default values 1 if no argument ispassed through the constructor. Class Calculator also contains a member function Calculate () that takes an operator (string) as an argument and compute it. Only four operators are allowed i.e. +, -, *, /


1
Expert's answer
2021-07-14T04:43:42-0400
using System;


namespace trip
{
    class Calculator
    {
        private int firstValue;
        private int secondValue;


        public Calculator(int x = 1, int y = 1)
        {
            firstValue = x;
            secondValue = y;
        }


        public int Calculate(string calcOperator)
        {
            if (calcOperator == "+")
                return firstValue + secondValue;
            else if (calcOperator == "-")
                return firstValue - secondValue;
            else if(calcOperator == "*")
                return firstValue * secondValue;
            else if(calcOperator == "/")
                return firstValue / secondValue;
            else
                throw new Exception("Wrong operator");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            var calc = new Calculator(4);
            Console.WriteLine(calc.Calculate("+"));
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS