Normally for this kind of task I write a helper method that takes in a string "prompt" (which is the question being asked to the user) and one or more valid responses. Then the method repeatedly asks the question in a do/while
loop whose condition is that the response is one of the valid answers.
Note that it's usually a good idea to give the user some choices for valid input (y/n)
so they have some idea why you keep asking them the same question over and over again if they enter something else. Though they may be pleasantly surprised if you accept other answers, like "sure"
or "nope"
.
In the example below, this method returns a bool
, and takes in two lists of valid answers: valid true
answers, and valid false
answers. This way it only returns true
or false
, but accepts a wide variety of input from the user:
public static bool GetBoolFromUser(string prompt, List<string> validTrueResponses,
List<string> validFalseResponses, StringComparison comparisonType)
{
string response;
// Combine all valid responses for the sake of the loop
var allValidResponses =
validTrueResponses?.Union(validFalseResponses) ?? validFalseResponses;
do
{
Console.Write(prompt);
response = Console.ReadLine();
} while (allValidResponses != null &&
!allValidResponses.Any(r => r.Equals(response, comparisonType)));
// Now return true or false depending on which list the response was found in
return validTrueResponses?.Any(r => r.Equals(response, comparisonType)) ?? false;
}
Then, in our main code we can create two lists of valid responses, pass them along with a prompt to the method above, and we know it will return us a true
or false
result that we can use to make a decision:
private static void Main()
{
// Add any responses you want to allow to these lists
var trueResponses = new List<string>
{
"y", "yes", "ok", "sure", "indeed", "yep", "please", "true"
};
var falseResponses = new List<string>
{
"n", "no", "nope", "nah", "never", "not on your life", "false"
};
bool openDoor = GetBoolFromUser("Do you want to open the door? (y/n): ",
trueResponses, falseResponses, StringComparison.OrdinalIgnoreCase);
if (openDoor)
{
Console.WriteLine("Ok, opening the door now!");
}
else
{
Console.WriteLine("Ok, leaving the door closed!");
}
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Here's what it looks like if you run it and give some bad responses...
