I have a method to check if the user wants to play another game, the problem is that if the user enters an invalid input then after a correct input anotherGame
is still set to Y
When it exits the method the value of anotherGame
is still Y
even if they select N
if they enter an incorrect input
When this block of code runs anotherGame
is returning Y
no matter what.
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
CODE EXAMPLE:
using System;
public class Program
{
public static void Main()
{
string anotherGame = "y";
while (anotherGame == "y")
{
anotherGame = promptRedo(anotherGame);
Console.WriteLine(anotherGame);
}
}
static String promptRedo(String anotherGame)
{
Console.Write("Would you like to play another game? (Y/N) => ");
String input = Console.ReadLine().ToLower();
if (input.Equals("y"))
{
anotherGame = "y";
}
else if (input.Equals("n"))
{
// get any key from user to exit program
Console.WriteLine();
Console.WriteLine("Thank you for playing!");
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
anotherGame = "n";
Console.WriteLine(anotherGame);
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
return anotherGame;
}
}
You don't need the recursive call, all you need to do is to remove
promptRedo(anotherGame);
From the else section inside promptRedo
function.
This function does not need an argument to be passed. instead of calling function again and againg just put it in a loop:
static String promptRedo()
{
String anotherGame = ""
do
{
Console.Write("Would you like to play another game? (Y/N) => ");
String input = Console.ReadLine().ToLower();
if (input.Equals("y"))
{
anotherGame = "y";
}
else if (input.Equals("n"))
{
// get any key from user to exit program
Console.WriteLine();
Console.WriteLine("Thank you for playing!");
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
anotherGame = "n";
Console.WriteLine(anotherGame);
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
}
} while(anotherGame != "y" && anotherGame != "n")
return anotherGame;
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
In this code you are just calling promptRedo() and returning anotherGame at the end of function. But you are supposed to return from promptRedo().
Your code must be like below
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
return promptRedo(anotherGame);
}
you haven't assigned the of "promptRedo(anotherGame)" method to "anotherGame" variable in else block.
Instead of:
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
you should write:
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
anotherGame = promptRedo(anotherGame);
}
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.