繁体   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