While循环不工作
本文关键字:工作 循环 While | 更新日期: 2023-09-27 18:04:22
有人能找到为什么这个循环不工作吗?我是c#新手。
while (move == "r" || move == "s" || move == "f")
{
Console.Write("'nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("'nYou have reloaded, press enter for Genius");
Console.ReadLine();
break;
case "s":
Console.Write("'nYou have shielded, press enter for Genius");
Console.ReadLine();
break;
case "f":
Console.Write("'nYou have fired, press enter for Genius");
Console.ReadLine();
break;
default:
Console.Write("'nInvalid move, try again'n'n");
break;
}
}
可能是因为move是在循环内初始化的,并且可能是null或空字符串,因为在循环之前我看不到代码,所以我假设它没有初始化。
我的建议是使用布尔标志,设置为
bool done = false;
while (!done)
{
// do work
if (move == finalMove) // or whatever your finish condition is
done = true; // you could also put this as a case inside your switch
}
耶稣是对的,建议你接受他的回答。下面是重写代码的方法。
do
{
Console.Write("'nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("'nYou have reloaded, press enter for Genius");
Console.ReadLine();
break;
case "s":
Console.Write("'nYou have shielded, press enter for Genius");
Console.ReadLine();
break;
case "f":
Console.Write("'nYou have fired, press enter for Genius");
Console.ReadLine();
break;
default:
Console.Write("'nInvalid move, try again'n'n");
break;
}
}
while (move == "r" || move == "s" || move == "f");
但是,请注意,如果您得到的不是"r","s"或"f",则将打印Invalid move, try again
,然后退出循环(它们不能再尝试)。相反,您可能需要分配一个键(可能是"q"表示quit)来终止循环并将while
条件更改为类似
的内容while (move != "q");