1

Im trying to convert a string called symbol into an operator (+ = - /) for a calculator. Instead of having only one symbol that is already chosen before, the user will choose what symbol to use (the result wont work since its not an operator).

 class Program
{
    static void Main(string[] args)
    {
        double num01;
        double num02;
        string symbol;
        Console.WriteLine("Input a number");
        num01=Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Write the second number");
        num02=Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Choose a mathematic symbol");
        symbol=Convert.ToString(Console.ReadLine());
        double result = ( num01 symbol num02 );
        Console.WriteLine ("The result is " + result); 
        Console.ReadKey();
    }
}
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
spe3dy
  • 11
  • 2

1 Answers1

3

You should create an additional method that will take your symbol and integers and perform the necessary calculation.

private int Calculate(string operator, int number1, int number2)
{
    if (operator == "+")
    {
        return number1 + number2;
    }
    else if (operator == "-")
    {
        return number1 - number2;
    }
    else if (operator == "*")
    {
        return number1 * number2;
    }
    else if (operator == "/")
    {
        return number1 / number2;
    }
    else
    {
        throw new ArgumentException("Unexpected operator string: " + operator);
    }    
}
ddastrodd
  • 710
  • 1
  • 10
  • 22