class Program
{
static void Main(string[] args)
{
string Studentname;
string retry = "No";
Console.WriteLine("What is the Student's name? ");
while (retry != "No")
Console.WriteLine("What is the Student's name? ");
Studentname = Console.ReadLine();
switch (Studentname) {
case "George":
Console.WriteLine("Yes in the list");
Console.ReadLine();
break;
case "Goblin":
Console.WriteLine("Yes in the list");
Console.ReadLine();
break;
case "Peter":
Console.WriteLine("Yes in the list");
Console.ReadLine();
break;
case "TJ":
Console.WriteLine("Yes in the list");
Console.ReadLine();
break;
default:
Console.WriteLine("Not in the list");
Console.WriteLine("Would you like to retry?");
retry = Console.ReadLine();
break;
}
}
}
如果答案不正确,我试图循环使用case语句,但是语句总是会中断,我无法循环。我该如何解决这个问题?
答案 0 :(得分:2)
关键字“break”只会突破第一个代码块(它位于{...}之间的空间)。交换机的中断不应该干扰你的while循环。
问题是你的while循环之后没有括号,因此它只会直接作用于该行。
以下可能就是你要找的东西。
class Program
{
static void Main(string[] args)
{
string Studentname;
string retry = "No";
Console.WriteLine("What is the Student's name? ");
do
{
Console.WriteLine("What is the Student's name? ");
Studentname = Console.ReadLine();
switch (Studentname)
{
case "George":
Console.WriteLine("Yes in the list");
//Console.ReadLine();
break;
case "Goblin":
Console.WriteLine("Yes in the list");
//Console.ReadLine();
break;
case "Peter":
Console.WriteLine("Yes in the list");
//Console.ReadLine();
break;
case "TJ":
Console.WriteLine("Yes in the list");
//Console.ReadLine();
break;
default:
Console.WriteLine("Not in the list");
Console.WriteLine("Would you like to retry?");
retry = Console.ReadLine();
break;
}
} while (retry != "No");
}
}
编辑:你的while循环也从未输入过。您将“重试”设置为“否”,然后检查它是否不是“否”。要解决这个问题,您可以使用“do ... while()”循环,它总是循环至少一次,或者您可以将“重试”的第一个分配更改为除“否”之外的任何内容。
编辑2:@Kason是正确的。如果找到名字,我没有意识到你的实际目标是退出。如果是这种情况,那么“do ... while()”是您的最佳选择。答案 1 :(得分:0)
相反,你可以使用这个简单的LINQ方法:
O(n + m) = O(n)
但是它没有用,因为你已经忘了把string Studentnames[] = new string[]
{
"George",
"Goblin",
"Peter",
"TJ"
}
while (retry != "No")
{
if (Studentnames.Contains(Studentname)
{
Console.WriteLine("Yes in the list");
Console.ReadLine();
}
else
{
Console.WriteLine("Not in the list");
Console.WriteLine("Would you like to retry?");
retry = Console.ReadLine();
}
}
放在while语句中。
答案 2 :(得分:0)
在while语句后面添加一个左大括号,在代码底部添加一个匹配的右大括号。
答案 3 :(得分:0)
while
循环开头后没有花括号。这意味着while
语句仅适用于紧随其后的行。
while (retry != "No")
Console.WriteLine("What is the Student's name? ");
如上所述,retry
以" No"开始。因此,当评估while
条件时,它是错误的。以下行永远不会执行,因为它只能在retry != "No"
时执行。
如果希望while
应用于一个语句块,请将它们放在大括号中。
while (retry != "No")
{
//Everything inside these braces will execute if retry != "No".
//If it gets to the end and retry still != "No" then it will repeat.
//You'd most likely want to do something inside this loop sooner or
//later that changes retry to something else so that the loop can
//end. Or you can use "break" to exit the loop.
}