【问题标题】:How do I check if value exists in array如何检查数组中是否存在值
【发布时间】:2021-09-18 12:34:11
【问题描述】:

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

如果用户输入中没有提到列出的运算符,我希望程序给出错误消息。

这是我的代码:

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)

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

【问题讨论】:

  • 您的问题实际上是“如何检查数组中是否存在元素?”?如果是,您的答案是here。如果不是,您能否更准确地解释您的意思?

标签: c# compiler-errors try-catch


【解决方案1】:

试试

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

【讨论】:

    【解决方案2】:

    您正在尝试检查该操作是否包含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();
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      相关资源
      最近更新 更多