0

I'm new to c#, But have I can code in Lua, and I'm trying to use some of my skills where necessary so I am trying to Concatenate the operator of the players choice to get them a result.

I've tried searching google for a solution, and I have tried to print it with out concatenating it in different ways, but I just cant figure out what to do.

using System;

namespace FirstConsoleProject
{
    class Program
    { 
        static void Main(string[] args) //This is a Method, named "Main". It's called when the program starts
        {
            int numberOne;
            int numberTwo;
            string method;

            Console.WriteLine("What would you like to do? <+, -, *, />");
            method = Console.ReadLine();
            Console.Write("Please type the first number: ");
            numberOne = Convert.ToInt32(Console.ReadLine());
            Console.Write("Please type the second number: ");
            numberTwo = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(numberOne + method + numberTwo + " = " + numberOne + method + numberTwo);
            Console.ReadKey();

        }
    }
}

I expect the out put to say "numberOne+numberTwo= ANSWER", not "numberOne+numberOne = numberOne + numberTwo".

1 Answers1

1

You'll need some sort of expression engine to do this. That could be as simple as a switch statement as you only have 4 operators up to and including something like FLEE.

The former case is pretty easy to code:

class Program
{ 
    static void Main(string[] args) //This is a Method, named "Main". It's called when the program starts
    {
        double numberOne;
        double numberTwo;
        string method;

        Console.WriteLine("What would you like to do? <+, -, *, />");
        method = Console.ReadLine();
        Console.Write("Please type the first number: ");
        numberOne = Convert.ToDouble(Console.ReadLine());
        Console.Write("Please type the second number: ");
        numberTwo = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine(numberOne + method + numberTwo + " = " + Calculate(numberOne,numberTwo,method));
        Console.ReadKey();

    }
    static double Calculate(double input1, double input2, string operator)
    {
        switch(operator)
        {
            case "+": return input1 + input2;
            case "-": return input1 - input2;
            case "*": return input1 * input2;
            case "/": return input1 / input2;
            default: throw new InvalidOperatorinException($"Unknown operator: {operator}");
        }
    }

}
Jamiec
  • 133,658
  • 13
  • 134
  • 193