如何检查数组中是否存在值

How do I check if value exists in array

我是编程新手,目前正在开发计算器程序。

我希望程序在用户输入中提到 none 个列出的运算符时给出错误消息。

这是我的代码:

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:");
    }
}

但是,它说不能对字符串和数组使用 != 运算符。 (编译器错误 CS0019)

如何检查用户输入(运算符)是否在数组中,以便抛出新的异常?

尝试

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

您正在尝试检查操作是否 包含func 数组中。 但是行 operation != func 检查操作是否 等于 到数组。

您需要改为循环数组并检查数组中是否有等于操作的元素:

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();