有人能找到为什么这个循环不起作用?我是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;
}
}
答案 0 :(得分:3)
可能因为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
}
答案 1 :(得分:1)
耶稣是对的,建议你接受他的回答。以下是您可以重写代码的方法。
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”表示退出),它会终止循环并将while
条件更改为
while (move != "q");