我正在进行C#任务并且已经完成了很多工作,除了我无法弄清楚如何根据用户回答“是”或“否”重播循环。如果他们回答是,我希望循环重播,如果他们回答否,它将留下一个很好的告别消息。
这是我的代码(为简单起见删除了我的评论):
Random randomNumber = new Random();
int count = 0;
int actualNumber = randomNumber.Next(1, 50);
int userGuess = 0;
bool correct = false;
Console.WriteLine("In this program you will be prompted to guess a number between 1 and 50 \n\n" +
"I'll help by saying if your guess is higher/lower than the actual number\n\n\n\n" +
"I'm thinking of a number between 1 and 50, please enter your guess.\n\n");
while (!correct)
{
count++;
Console.Write("Guess: ");
string input = Console.ReadLine();
if (!int.TryParse(input, out userGuess))
{
Console.WriteLine("That's not a number between 1 and 50, please try again.");
continue;
}
if (userGuess < actualNumber)
{
Console.WriteLine("Sorry, the number is higher than that, keep guessing!");
}
else if (userGuess > actualNumber)
{
Console.WriteLine("Sorry, the number is lower than that, keep guessing!.");
}
else
{
correct = true;
Console.WriteLine("{0} is the right number! It took you {1} times to guess", userGuess, count);
}
}
我无法弄清楚我是否应该使用另一个while语句或if / else或者使用它的内容和位置。我在这里搜索过,发现了不同语言的类似问题,但C#没有。我将不胜感激任何帮助。谢谢!
答案 0 :(得分:4)
您可以将代码置于do-while
循环内。它会询问用户是否要重播?如果用户输入是,则游戏将重新开始。
Random randomNumber = new Random();
do
{
int actualNumber = randomNumber.Next(1, 50);
int count = 0;
int userGuess = 0;
bool correct = false;
Console.Clear();
Console.WriteLine("In this program you will be prompted to guess a number between 1 and 50 \n\n" +
"I'll help by saying if your guess is higher/lower than the actual number\n\n\n\n" +
"I'm thinking of a number between 1 and 50, please enter your guess.\n\n");
while (!correct)
{
// ...your code
}
Console.WriteLine("Do you want to replay?");
} while (Console.ReadLine().ToUpper() == "YES");
P.S: 如上所示,在循环外部初始化Random
,否则会生成相同的数字。