Reputation: 27
I am writing a method to take user input for a menu with three options: 1,2,3. My do while loop runs, however my while logic is still accepting unwanted input. Why is my code not looping for inputs outside of my set range of values?
I have tried different logical operators, removing logical operators and setting while Option < Value.
private static MenuOption ReadUserOption()
{
int Option;
Console.WriteLine("Please make a selection");
Console.WriteLine("1, will run TestName, 2 will run Guess that number, 3 Wil quit the program.");
do
{
Option = Convert.ToInt32(Console.ReadLine());
return (MenuOption)(Option - 1);
} while (Option < 1 || Option > 3);
}
My goal is for any user input outside of <1 and >3 for the loop to continue until a value within that range is entered. In its current state if I enter 0 the loop will accept that value and output -1.
Upvotes: 0
Views: 82
Reputation: 4394
You just need to move the return statement outside the loop
private static MenuOption ReadUserOption()
{
int Option;
Console.WriteLine("Please make a selection");
Console.WriteLine("1, will run TestName, 2 will run Guess that number, 3 Wil quit the program.");
do
{
Option = Convert.ToInt32(Console.ReadLine());
} while (Option < 1 || Option > 3);
return (MenuOption)(Option - 1);
}
Upvotes: 3