I'm trying to build a calculator in C# for practice. My first step is to parse the user-input equation. For troubleshooting purposes, I'm trying to see if my parser can differentiate between numbers and operation symbol (e.g. "+", "-", "/", etc). The idea is to compare the user-input operation to a character array containing the allowed operations (+, -, /, *). If one of these allowed operation is inputted by the user, the code should say it is an allowed operation. The code to do that is shown below:
public static void ProcessEq(string equation)
{
//Parse the equation using regular expression
equation = equation.Replace(" ", "");
char[] operations = { '+', '-', '*', '/' };
string[] parts = Regex.Split(equation, @"(?<=[-+*/()])|(?=[-+*/()])");
foreach (string item in parts)
//Console.WriteLine(item + " is being tested...");
try
{
float num = Int32.Parse(item);
Console.WriteLine(item + " is a number");
}
catch(FormatException)
{
if ( Array.IndexOf(operations, item) > -1 )
{
Console.WriteLine(item + " is a valid operation");
}
else
{
Console.WriteLine(item + " is NOT a valid operation");
}
}
}
The if-condition is not picking up on any of the allowed operation symbols. If I type in 2+2, it keeps just passing into the else-condition and saying that the user inputted operation is not valid. Is my if-condition flawed?
Thanks