我想验证用户输入并确保它在我的字符范围内(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
和使事情更加容易。
感谢您的回答。我修改了我原来的请求,我也不能使用数组。另外,对于我的问题,我想了解为什么我后来做的没有工作,为什么我的工作。 – glls
将其编辑为准确回答您的问题,并简化了代码。希望它有助于:) – Royar
它确实。谢谢! – glls