How do I check if value exists in array

Viewed 124

I'm new to programming and am currently working on a calculator program.

I want the program to give an error message if none of the listed operators are being mentioned in the user input.

Here's my code:

int Number = 0;
string operation = "0";
string[] func = { "+", "-", "*", "/", ":", "x^2", "%", "cos", "bin" };

 while (true)
 {
    try
    {
        Number = Int32.Parse(Console.ReadLine());
        Console.WriteLine("--------------------------------------------");
        Console.WriteLine("Choose your operation: \n \n + \n - \n * \n : \n x^2 \n % \n cos \n bin");
        Console.WriteLine("--------------------------------------------");
        operation = Console.ReadLine();

        if (operation != func)
        {
            throw new Exception();
        }

        Console.WriteLine("--------------------------------------------");
        break;
    }
    catch (Exception)
    {
        Console.Clear();
        Console.WriteLine("Error! Please try again:");
    }
}

But, it says cannot use the != operator with a string and an array. (Compiler Error CS0019)

How can I check if a user input (operator) is in an array, so I can throw a new exception?

2 Answers

Try

if (!func.contains(operation)) 
{ 
    throw new Exception("");
}

You are trying to check if the operation is included in func array. but the line operation != func checks if operation is not equal to array.

You need to loop the array instead and check if there is an element in the array that is equal to operation:

bool found = false;
for (int i = 0; i < func.Length; i++)
    if (operation == func[i])
          found = true;
if (found == false)  // operation is not found
    throw new Exeption();
Related