簡體   English   中英

創建帶有開關狀態,循環和列表的菜單?

[英]Create menu with switch-statement, loop and list?

我正在使用一個菜單,希望在菜單選項內使用switchlist 我還想循環執行此程序,直到用戶決定退出(通過選擇菜單中的最后一個選項)。

我被卡住是因為我不知道如何執行循環或第一個菜單選擇的list 我希望用戶能夠在包中添加任意數量的東西,例如“貓”,“狗”,“汽車”等。

這是我的代碼目前的樣子:

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();
    }
}

我要做的是:

  1. 由於您可以選擇單獨包裝“外層隔層”而不是包裝主袋,因此為此創建一個單獨的列表。 因此,我將擁有mainCompartmentouterCompartment列表。
  2. 將您的選擇選項包裝在while循環內,以便您可以繼續提出問題,直到用戶退出為止。 這將需要某種類型的標志,因此我們知道何時退出,因此創建一個名為allDone的布爾值(以false開頭),如果用戶選擇選項4,則將其設置為true
  3. 對用戶輸入進行一些驗證,以確保他們從1到4之間選擇一個數字。最簡單的方法是檢查int.TryParse的結果,因為如果輸入不是int它將返回false,並將其合並用邊界檢查數字是否為1-4。
  4. 將用於將物品放入袋子並將袋子內容顯示的真實代碼放入單獨的函數中,然后從switch語句調用它們。 這將使您的主體代碼更易於閱讀。
  5. 將要求用戶輸入項目的代碼放入循環中,並為他們提供一些關鍵字以在完成時進行鍵入。 這個詞將成為退出循環的標志。

完成后,主要代碼如下所示:

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();
}

還有主要代碼調用的兩個幫助器函數:

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);
    }
}

嘗試這個:

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");
    }
}

真正的答案:使用按鈕和彈出窗口創建UI ;-)

該修復程序會引起我很多反對(警告:“此解決方案被認為是有害的...”)

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:
}

當然沒有經過測試。

這也是一個可怕的懶惰修復...您可以將其轉換為do,while等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM