gpt4 book ai didi

java - 如何在 "Guess my number "游戏中使用Do While循环?

转载 作者:行者123 更新时间:2023-12-01 18:07:35 25 4
gpt4 key购买 nike

我正在执行一个名为“猜我的号码”的简单任务,我正在尝试实现我的代码,以便当用户猜到正确的数字时,应用程序会显示“恭喜”并允许用户选择是否再次玩。我认为 do while 循环可以做到这一点,但我仍然不确定如何实现它。有任何想法吗?。提前谢谢您!

这是我的代码,运行得很好。

        Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());

if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}
}

最佳答案

您可以在最外层循环中添加一个 boolean 标志,以便在用户说“否”时中断:

Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
bool retry = true;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());

if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}

}
if (!retry) break;

}

对于 do-while 版本:

    bool retry = true;
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;

while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());

if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}

}
} while (retry);

关于java - 如何在 "Guess my number "游戏中使用Do While循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com