[英]C# Do-While statement to validate user input
我想创建一个简单的do-while语句,以确保用户输入的内容是Y或N,如果没有,请他们再次输入。 如果是Y或N,则应用继续。 到目前为止,这是我所拥有的,但是我的应用程序虽然陷入了一个循环,要求用户输入。 C#的新手-感谢您的帮助。
string answer = "";
do
{
//Ask the user if they want to roll the dice
Console.WriteLine("Would you like to roll the dice (y or n)?");
//Get the user's response and validate that it is either 'y' or 'n'.
answer = Console.ReadLine();
} while (answer != "Y" || answer != "N");
看起来像一个简单的布尔逻辑错误。
您的while语句应为:while(answer!=“ Y” && answer!=“ N”);
因为您要确保答案不是Y,答案也不是N。因此,请循环两次。 希望这可以帮助!
您的逻辑是OR ||
代替AND &&
。 它总是不是Y
或不是N
因为它不能一次都为。 当它为N
时不是Y
,反之亦然。
使用AND &&
代替。
另外,您的比较区分大小写。 考虑检查大小写。
更改|| 到&&,这应该可以为您解决。
另一种查看方式可能是:
中断条件是答案为“ Y”或答案为“ N”。
您希望在不满足中断条件时继续循环,这样您就可以
(answer ==“ Y” || answer ==“ N”),然后不是结果
while(!(answer == "Y" || answer == "N")
2件事
||
与&&
Y
& N
匹配,导致用户可以输入y
。 Y
和y
都是用户的积极决定。 answer.ToUpper() != "Y" && answer.ToUpper() != "N"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.