I'm working on a C# assignment and am pretty much done, except I cannot figure out how to replay the loop based on the user answering "yes" or "no." If they answer yes I want the loop to replay, if they answer no, it will leave a nice goodbye message.
Here's my code (deleted my commenting for simplicity):
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);
}
}
I'm having trouble figuring out if I should use another while statement or an if/else or what and where to use it. I've searched here and found similar questions for different languages, but nothing for C#. I would appreciate any help. Thanks!
You can place your code inside do-while
loop. And it will ask from user if he or she wants to replay? And if user enters Yes , then the game will start again.
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");
PS: Initilize Random
outside the loop as example in above, otherwise it will generate same number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.