DanielRoberts DanielRoberts - 2 months ago 7
C# Question

Ask user to re-input a response if it is not a valid response C#

So I am creating a game that is a command line game in C#, using Visual Studio. What I am wanting to do is ask a question and get the response either 'Y' or 'N'.
I want to be able to have it so that if the response is not either of those, it just repeats the question for them to give a correct response. I am not able to find a good way to do this, as I have not had to do this before. Can anyone help me with this?

Thanks in advance!

Answer

You have to simply re-ask for the response until you get the valid one. A method like this can work for your case:

static void GetResponse()
{
    Console.WriteLine("Do you wish to continue? [Y/N]");

    var keyInfo = Console.ReadKey(); //Read a single key from the user. The ReadKey method displays the pressed key on the console.

    //Check the pressed key and if it's not y or n, re-ask for it.
    while (keyInfo.KeyChar.ToString().ToLower() != "y" && keyInfo.KeyChar.ToString().ToLower() != "n")
    {
        Console.WriteLine();
        Console.WriteLine("Invalid choice. Valid choices are: Y or N");
        keyInfo = Console.ReadKey(); //Retake the input.

    }
    Console.WriteLine(); //For formatting purposes.
}

And then from your Main method, call the GetResponse method:

static void Main(string[] args)
{
    GetResponse();
    //Valid response received. Do something here...

}