So this is day 2 of me learning on my own, I'm sure this is a very beginner question here but looking up things I have found using typeof or tryparse but I can't seem to figure out how to use them. I probably shouldn't be trying this at this stage of learning but I figured I'd ask anyway because I really want to know how to do it. I'm following a tutorial but it doesn't cover if the user input is not a number. This is my basic calculator:
using System;
namespace Tutorials
{
class Program
{
static void Main(string[] args)
{
string opError = "Invalid Operator";
string numError = "Enter a valid number";
Console.Write("Enter a number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Operator: ");
string op = Console.ReadLine();
Console.Write("Enter a number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (op == "+")
{
Console.WriteLine(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine(opError);
}
Console.ReadLine();
}
}
}
I want to be able to check if a user input for num1 and num2 is a number, and if it isn't I want it to display a message which I have set for numError. Now the if and else statements make sense to me because I know the operators being used. When it comes to the user input, that could be anything. That's where I'm confused about how to go about doing this. I read about typeof and tryparse but I don't quite get how to use that in this code. I tried it with tryparse but once I enter a number, it doesn't do anything so I'm assuming I need an if statement in that which I'm still way too at the beginning to know how to do that. What would be the best way to do this with my code? I see there are better ways to do this calculator, I've seen some examples but I'm trying to understand it with the way I have it at the moment.