我试图制作一个简单的程序,询问用户是否要输入他们的名字。 我使用了do-while循环来执行此操作。如果答案为“ y”,则程序将打印文本并询问用户名称。如果答案为“ n”,则打印文本。在这两种情况下,循环都结束。如果用户输入的不是“ y”或“ n”,则循环重复并要求输入正确的值。 我的问题是,只要有人输入以字母“ y”开头的任何字符串,例如“ yes”或“ yeetjasdk”。发生这种情况时,代码将打印文本以询问用户正确的输入,但是,循环退出,程序结束。对于以'n'开头的单词,不会发生这种情况。
do { //Keep running loop until user
Console.Write("Welcome. Do you want to tell us your name? (y/n): "); //enters either y or n.
answer = Console.ReadLine(); //Ask user for input.
if (answer == "y") {
Console.Write("What is your name: ");
userName = Console.ReadLine();
Console.WriteLine("Welcome, {0}", userName);
}
else if (answer == "n") { Console.WriteLine("Acknowledged."); }
else { Console.WriteLine("Sorry, I didn't catch that."); }
} while((result = string.Compare(answer, "y", true)) < 0 || (result = string.Compare(answer, "n", true)) < 0);
答案 0 :(得分:0)
这行对我来说真的很奇怪:
while ((result = string.Compare(answer, "y", true)) < 0 || (result = string.Compare(answer, "n", true)) < 0);
string.Compare()
根据排序顺序执行大于/小于/等于比较。那似乎不是您想要的。
为什么不使用更简单的方法?如:
while (answer != "y" && answer != "n")
或者更好的是,一旦知道答案有效,就退出循环。这样一来,您无需再次检查条件,就可以确保逻辑一致。
while (true)
{
Console.Write("Welcome. Do you want to tell us your name? (y/n): ");
answer = Console.ReadLine();
if (answer == "y")
{
Console.Write("What is your name: ");
userName = Console.ReadLine();
Console.WriteLine("Welcome, {0}", userName);
break; // <-- exit the loop
}
if (answer == "n")
{
Console.WriteLine("Acknowledged.");
break; //<-- exit the loop
}
Console.WriteLine("Sorry, I didn't catch that."); }
}