2016-10-30 46 views
0

我想验证用户输入并确保它在我的字符范围内(3个选项a,b或c)。我设法使它工作,但我不明白为什么。虽然char.TryParse字符验证

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 验证什么用户输入的字符类型,以及|| !the.Character.Equals('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

有人可以解释为什么2下面的声明不工作,如果第一个声明实际上是要走的路?

对于我的家庭作业,theCharacter必须是一个char类型,并且不能使用array S,否则我会去用string和使事情更加容易。

回答

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'))) { 

    } 
+0

感谢您的回答。我修改了我原来的请求,我也不能使用数组。另外,对于我的问题,我想了解为什么我后来做的没有工作,为什么我的工作。 – glls

+0

将其编辑为准确回答您的问题,并简化了代码。希望它有助于:) – Royar

+0

它确实。谢谢! – glls