mardi 17 juillet 2018

How to make a efficient menu where the user has to input the full option?

I'm doing a menu screen where the user needs to input exactly one of the options. Currently I'm doing this:

static void Start()
    {
        Console.WriteLine("Options: " + Environment.NewLine);
        string[] options = { "Option 1", "Option 2", "Option 3" };
        foreach (string value in options)
        {
            Console.WriteLine(value);
        }
        Console.Write("Type the option you want: ");
        string choosen = Console.ReadLine();
        if(choosen == "Option 1")
        {
            Console.WriteLine(Environment.NewLine + "Your choosen option was Option 1" + Environment.NewLine);
            Start();
        }
        else if (choosen == "Option 2")
        {
            Console.WriteLine(Environment.NewLine + "Your choosen option was Option 2" + Environment.NewLine);
            Start();
        }
        else if(choosen == "Option 3")
        {
            Console.WriteLine(Environment.NewLine + "Your choosen option was Option 3" + Environment.NewLine);
            Start();
        }
        else
        {
            Console.WriteLine(Environment.NewLine + "Please choose a valid option!" + Environment.NewLine);
            Start();
        }
    }

I can tell it's not a very efficient way of doing it but I don't know any other way.

I know I could do it like this:

ConsoleKeyInfo key = Console.ReadKey();
        switch (key.Key)
        {
            case ConsoleKey.D1:
                Console.WriteLine(Environment.NewLine + "Your choosen option was Option 1" + Environment.NewLine);
                Start();
                break;
            case ConsoleKey.D2:
                Console.WriteLine(Environment.NewLine + "Your choosen option was Option 2" + Environment.NewLine);
                Start();
                break;
            case ConsoleKey.D3:
                Console.WriteLine(Environment.NewLine + "Your choosen option was Option 3" + Environment.NewLine);
                Start();
                break;
            default:
                Console.WriteLine(Environment.NewLine + "Please choose a valid option!" + Environment.NewLine);
                Start();
                break;
        }

But I want the user to write fully one of the the options, like "Option 1" or so. This way the user needs to press a single key.

So, is there a more efficient way of doing this, or for this exact purpose, I can only do the way I've been doing it? I really don't like having a if-else statement for each option I've got.

Aucun commentaire:

Enregistrer un commentaire