简体   繁体   中英

C# switch statement validation

I was wondering if there was a way to do something like this in C#:

some loop here
{
    Console.WriteLine("Please enter a or b");
    switch (Console.ReadLine().ToLower())
    {
        case "a":
            //some code here
            break;
        case "b":
            //some code here
            break;
        default:
            Console.WriteLine("Error, enter a or b");
            repeat loop
    }
}

It's probably a stupid question but something like that would be greatly beneficial to my assignment.

Why not. Run a while loop that exists only when a or b is entered.

bool condition = false;

Console.WriteLine("Please enter a or b");
string str = string.Empty;
while (!condition)
{
     str = Console.ReadLine().ToLower();
     switch (str)
     {
         case "a":
             //some code here
             condition = true;
             break;
         case "b":
             //some code here
             condition = true;
             break;
         default:
             Console.WriteLine("Error, enter a or b");
             break;
     }
 }
 Console.WriteLine("You have entered {0} ", str);
 Console.ReadLine();

What about something like this?

var acceptedValues = new List<string>()
{
    "a",
    "b",
};

Console.WriteLine("Please enter {0}", string.Join("or", acceptedValues));
var enteredValue = string.Empty;
do
{
    enteredValue = Console.ReadLine().ToLower();
} while (!acceptedValues.Contains(enteredValue));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM