if语句似乎不适用于多个条件

时间:2017-12-05 16:21:55

标签: c# .net

我不确定我是否会重载任何内容,但是当我将所需的所有条件添加到一个if语句时,它总是返回true。它似乎总是显示我的错误信息,但当我只添加一个条件时,它完全正常。另外,我知道我的代码很乱,我只是一个新手,对我很轻松。

Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (Vclass != "AA" || Vclass != "BB" || Vclass != "CC" || Vclass != "DD" || Vclass != "EE" || Vclass != "FF" || Vclass != "GG" || Vclass != "HH" || Vclass != "II" || Vclass != "JJ" || Vclass != "KK" || Vclass != "LL" || Vclass != "MM" || Vclass != "NN" || Vclass != "OO")
{
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("There is an error with the vehicle class.");
        Console.ForegroundColor = ConsoleColor.Green;
}

2 个答案:

答案 0 :(得分:3)

我有一碗水果。我想确保其中没有我不喜欢的水果。我喜欢的水果是:苹果香蕉葡萄 kiwis

所以我不喜欢的那些不是苹果 AND 不是香蕉 AND 不是葡萄 AND 不是 kiwis

我不喜欢的那些不是那些不是苹果 香蕉 OR grape OR kiwis

||相当于懒惰的 OR 。您的情况应该是使用惰性 AND &&

if (Vclass != "AA" && 
    Vclass != "BB" && 
    Vclass != "CC" && 
    Vclass != "DD" && /*..etc*/)

答案 1 :(得分:-1)

所以,基本上,你正在寻找这个:

Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (!Class.Contains(Vclass))
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("There is an error with the vehicle class.");
    Console.ForegroundColor = ConsoleColor.Green;
}