-2

Don't know how to convert String to int. I tried to replace the String type with a int but it wouldn't execute if I did. And when I tried to convert the String types to other things like double, float, bool, char etc.

using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What operation would you like? + - * /: ");
            String Operator = Console.ReadLine();
            Console.WriteLine("Type first number: ");
            String num1 = Console.ReadLine();
            Console.WriteLine("Type second number: ");
            String num2 = Console.ReadLine();
            if (Operator == "+")
            {
                Console.WriteLine(num1 + num2);
            }
            if (Operator == "-")
            {
                Console.WriteLine(num1 - num2);
            }
            if (Operator == "*")
            {
                Console.WriteLine(num1 * num2);
            }
            if (Operator == "/")
            {
                Console.WriteLine(num1 / num2);
            }

        }
    }
}
Dogo777
  • 7
  • 2

1 Answers1

-1

Instead of string num1 = Console.ReadLine(); use int num1 = Int32.Parse(Console.ReadLine());

Do this for num2 also. Keep in mind that if you input an invalid string you will get an exception. You can solve this by using the .TryParse() method or encapsulate the thing in Try-Catch. I would recommend .TryParse(), though because it's more optimized and generally viewed a more correct way of doing this.

Martin Ferenec
  • 57
  • 1
  • 1
  • 9