而char.TryParse字符验证

时间:2016-10-30 18:35:02

标签: c# validation char

我正在尝试验证用户输入并确保它在我的角色范围内(3个选项a,b或c)。我设法让它发挥作用,但我不太明白为什么。

char theCharacter;            
Console.WriteLine("{0}", "Enter a,b or c");

while (!char.TryParse(Console.ReadLine(), out theCharacter) || !theCharacter.Equals('a') )
{
    if (theCharacter.Equals('b'))
    {
        break;
    }
    else if (theCharacter.Equals('c'))
    {
        break;
    }
    else
    {
        Console.WriteLine("Please chose a valid character(a, b or c).");
    }
}

我理解(或相信)!char.TryParse(Console.Readline(), out theCharacter 验证用户输入的char类型,|| !the.Character.Equals('a')只会验证如果语句不为真(char不等于a),则用户将被提示输入a,b或c。

但是,如果我执行以下操作:

while (!char.TryParse(Console.ReadLine(), out theCharacter) || !theCharacter.Equals('a') || !theCharacter.Equals('b') || !theCharacter.Equals('c'))

无论我的输入是什么,用户都会陷入while循环, 如果我这样做:

while (!char.TryParse(Console.ReadLine(), out theCharacter) && (!theCharacter.Equals('a') == true || !theCharacter.Equals('b') == true || !theCharacter.Equals('c')== true))

无论我输入什么字符,都会被接受为theCharacter

有人可以解释为什么下面的两个陈述不起作用,如果第一个陈述实际上是要走的路?

对于我的作业,theCharacter必须是char类型,并且无法使用array,否则我会选择string并使事情变得更轻松

1 个答案:

答案 0 :(得分:1)

你的初始条件有效,因为只有在角色不是" a"如果角色也不是" b"它只会继续循环。或者" c",例如只有当角色不是" a"," b"或" c"。

然而,你的第二个条件是有缺陷的,因为它为每个与3个中的一个不同的字符重复循环:" a"," b"," C" (例如," a"不同于" b"因此它回答了条件。" m"与" a"不同回答条件)。世界上每个角色都回答了这个问题。 你要检查的是角色不是" a"并且不是" b"并且不是" c",就像这样:

!theCharacter.Equals('a') && !theCharacter.Equals('b') && !theCharacter.Equals('c')

完整代码:

    char theCharacter;
    while (!char.TryParse(Console.ReadLine(), out theCharacter) ||
           (!theCharacter.Equals('a') && !theCharacter.Equals('b') && !theCharacter.Equals('c'))) {

    }