简体   繁体   中英

Create menu with switch-statement, loop and list?

I'm working on a Menu where I want to use switch and list inside the menu choice. I also want to loop this program until the user decides to quit (by choosing the last option in the menu).

I'm stuck because I dont know how to do the loop, or the list for the first menu choice. I want the user to be able to add any number of things to the bag, like "cat", "dog", "car", etc.

This is how my code looks at the moment:

class Program
{
    static void Main(string[] args)
    {                       
        Console.Title = "5";
        Console.ForegroundColor = ConsoleColor.Blue;
        // ________________________________________________________

        Console.WriteLine("\n \t This is your bag!");
        Console.WriteLine("\t [1] to pack things");
        Console.WriteLine("\t [2] to pack things in the outercompartment");
        Console.WriteLine("\t [3] to see packed things");
        Console.WriteLine("\t [4] to quit");
        Console.WriteLine("\t your choice: ");
        string str = Console.ReadLine();
        int nr = Convert.ToInt32(str);
        List<string> items = new List<string>();
        items.Add(str);

        switch (nr)
        {
            case 1:
                Console.Write("What would you like to pack?\t");
                str = Console.ReadLine();
                break;
        }

        Console.ReadKey();
    }
}

What I would do is:

  1. Since you give the option to pack the "outer compartment" separately from packing the main bag, create a separate list for this. So I would have mainCompartment and outerCompartment lists.
  2. Wrap your choice options inside a while loop, so you can continue asking questions until the user quits. This will require some type of flag, so we know when to quit, so create a Boolean called allDone that starts as false , then set it to true if the user chooses option 4.
  3. Do some validation on the user input, to be sure they choose a number from 1 to 4. The easiest way is to check the result of int.TryParse , since it will return false if the input isn't an int, and combine this with the bounds check that the number is from 1-4.
  4. Put the real code for getting items into the bag and displaying bag contents into separate functions, and then call them from the switch statement. This will make your main body of code much easier to read.
  5. Put the code that asks the user to enter items into a loop, and give them some keyword to type when they're done. This word will become the flag to exit the loop.

Here's how the main code might look when finished:

private static void Main()
{
    Console.Title = "5";
    Console.ForegroundColor = ConsoleColor.Blue;

    List<string> outerCompartment = new List<string>();
    List<string> mainCompartment = new List<string>();

    bool allDone = false;

    while (!allDone)
    {
        Console.WriteLine("\nThis is your bag!");
        Console.WriteLine("[1] to pack things in the main compartment");
        Console.WriteLine("[2] to pack things in the outer compartment");
        Console.WriteLine("[3] to see packed things");
        Console.WriteLine("[4] to quit");
        Console.WriteLine("Please enter your choice: ");

        int choice;
        while (!int.TryParse(Console.ReadLine(), out choice) || choice < 1 || choice > 4)
        {
            Console.WriteLine("Invalid input. Enter a number from 1 to 4: ");
        }

        switch (choice)
        {
            case 1:
                GetItemsAndAddToCompartment(mainCompartment, "main");
                Console.Clear();
                break;
            case 2:
                GetItemsAndAddToCompartment(outerCompartment, "outer");
                Console.Clear();
                break;
            case 3:
                DisplayCompartmentContents(mainCompartment, "Main");
                DisplayCompartmentContents(outerCompartment, "Outer");
                break;
            case 4:
                Console.WriteLine("All done. Have a great trip!");
                allDone = true;
                break;
        }
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

And the two helper functions that are called by the main code:

static void GetItemsAndAddToCompartment(List<string> compartment, string compartmentName)
{
    if (compartment == null) throw new ArgumentNullException(nameof(compartment));
    Console.WriteLine($"Enter items to add to {compartmentName} compartment below. Type 'done' when finished.");

    int counter = 1;
    while (true)
    {
        Console.Write($"Enter item #{counter++}: ");
        string item = Console.ReadLine();
        if (item.Equals("done", StringComparison.OrdinalIgnoreCase)) break;
        compartment.Add(item);
    }
}

static void DisplayCompartmentContents(List<string> compartment, string compartmentName)
{
    Console.WriteLine($"{compartmentName} compartment contents");
    Console.WriteLine("-------------------------");
    if (compartment == null || !compartment.Any())
    {
        Console.WriteLine("[No items in this compartment]");
    }
    else
    {
        compartment.ForEach(Console.WriteLine);
    }
}

Try this:

class Program
{
    static void Main(string[] args)
    {
        PrintMenu();
        List<string> lBag = new List<string>();
        bool bQuit = false;
        int iChoice = -1;
        string sIn = string.Empty;

        while (!bQuit)
        {
            sIn = Console.ReadLine();
            if (!Int32.TryParse(sIn, out iChoice) || !(iChoice >= 1 && iChoice <= 3))
            {
                Console.WriteLine("\t Invalid input. Try again:");
                PrintMenu();
                continue;
            }

            switch (iChoice)
            {
                case 1:
                    Console.WriteLine("\t Insert the item you want to add:");
                    lBag.Add(Console.ReadLine());
                    Console.WriteLine("\t Item added successfully.");
                    PrintMenu();
                    break;
                case 2:
                    Console.WriteLine(string.Format("\t Current bag: [{0}]\n", string.Join(", ", lBag)));
                    PrintMenu();
                    break;
                case 3:
                    Console.WriteLine("\t Quitting...");
                    bQuit = true;
                    break;
                default:
                    break;
            }
        }
    }

    static void PrintMenu()
    {
        Console.WriteLine("\n Please choose one of the options below:");
        Console.WriteLine("\t [1] Add item to bag");
        Console.WriteLine("\t [2] Display the bag");
        Console.WriteLine("\t [3] Quit");
    }
}

The real answer: Make a UI with buttons and popups ;-)

A fix that will get a me a lot of downvotes (Warning: 'this solution considered harmful...')

class Program
{
    static void Main(string[] args)
    {                       
        Console.Title = "5";
        Console.ForegroundColor = ConsoleColor.Blue;
        // ________________________________________________________
        loop:
        Console.WriteLine("\n \t This is your bag!");
        Console.WriteLine("\t [1] to pack things");
        Console.WriteLine("\t [2] to pack things in the outercompartment");
        Console.WriteLine("\t [3] to see packed things");
        Console.WriteLine("\t [4] to quit");
        Console.WriteLine("\t your choice: ");
        string str = Console.ReadLine();
        int nr = Convert.ToInt32(str);
        List<string> items = new List<string>();
        items.Add(str);

        switch (nr)
        {
            case 1:
                packing:
                Console.Write("What would you like to pack? [QUIT for menu]\t");
                str = Console.ReadLine();
                if (str=="QUIT") goto loop;
                items.add(str);
                Console.WriteLine("You packed a " + str);
                goto packing;
                break;
            case 4:
                goto quitloop;

        }

        Console.ReadKey();
        goto loop;
    }
quitloop:
}

Not tested of course.

Also this is a terrible lazy fix ... you can convert this do do, while, etc.

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