[英]issue with While Loops C#
我有一个石头剪刀布程序,它会询问您的输入,进行随机 cpu 输入,比较它们,然后宣布该轮的获胜者。 我试着做一个while循环,当一轮结束时,它会再次播放,直到有人达到3分。 一轮结束后,程序似乎中断了。 我已经引用了while循环。 谢谢!
string playerInput;
string cpuInput;
int randomInt;
bool playAgain = true;
int scorePlayer = 0;
int scoreCPU = 0;
while (scorePlayer > 3 && scoreCPU > 3);
{
Console.WriteLine("Rock Paper or Scissors?");
playerInput = Console.ReadLine();
playerInput.ToLower();
Random rnd = new Random();
randomInt = rnd.Next(1, 4);
switch (randomInt)
{
case 1:
cpuInput = "rock";
Console.WriteLine("CPU chose rock");
if (playerInput == "rock")
{
Console.WriteLine("DRAW!");
}
else if (playerInput == "paper")
{
Console.WriteLine("PLAYER WINS!");
scorePlayer++;
}
else if (playerInput == "scissors")
{
Console.WriteLine("CPU WINS!");
scoreCPU++;
}
break;
case 2:
cpuInput = "paper";
Console.WriteLine("CPU chose paper");
if (playerInput == "rock")
{
Console.WriteLine("PLAYER WINS");
scorePlayer++;
}
else if (playerInput == "paper")
{
Console.WriteLine("DRAW!");
}
else if (playerInput == "scissors")
{
Console.WriteLine("CPU WINS!");
scoreCPU++;
}
break;
case 3:
cpuInput = "scissors";
Console.WriteLine("CPU chose scissors");
if (playerInput == "rock")
{
Console.WriteLine("CPU WINS!");
scoreCPU++;
}
else if (playerInput == "paper")
{
Console.WriteLine("PLAYER WINS!");
scorePlayer++;
}
else if (playerInput == "scissors")
{
Console.WriteLine("DRAW!");
}
break;
default:
Console.WriteLine("INVALID INPUT!");
break;
if (scorePlayer == 3)
{
Console.WriteLine("PLAYER WON!");
}
else if (scoreCPU ==3);
{
Console.WriteLine("CPU WON!");
}
}
}
Console.ReadLine();
问题出在这里:
int scorePlayer = 0;
int scoreCPU = 0;
while (scorePlayer > 3 && scoreCPU > 3);
scorePlayer
和scoreCPU
都不大于 3,因此循环条件失败。 末尾的分号是一个空语句。 接下来的所有内容都在代码块中,但不是while
循环的内容。
删除分号并更改您的条件以允许循环条件最初成功。
例如:
while (scorePlayer < 3 && scoreCPU < 3)
使用调试器检查变量的内容将帮助您理解为什么您的循环不起作用,并且一旦条件正确,您就会看到它踩到分号上。
根据您提到的程序描述,它应该运行到播放器或 CPU 之一有 3 个点,允许 While 循环运行,直到它满足中断条件。
将您的 While 循环条件更改为:
while(scorePlayer < 3 && scoreCPU < 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.