繁体   English   中英

我如何让用户在 C# 中按他们希望的任何顺序选择 5 个项目?

[英]How can i let a user choose between, let's say 5 items in any order they wish in C#?

我试图在控制台上为我的用户提供 5 个选项,我希望他们能够从菜单中选择多个选项。 我计算出用户可以在 5 种选择中选择 31 种方式。 我试图为它写一个开关/案例,但为它写 31 个案例似乎不合逻辑。 还有其他方法吗? 我会感谢你们帮我解决这个问题

namespace Homework_2
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("a-cake b-milk c-noodles d-cheese e-coke:");
            string choice = Console.ReadLine();
            switch (choice)
            {
                default:
                    break;
            }

        }
    }
}

所以你希望用户做出选择然后计算总成本? 我建议像这样遍历字符串

int total = 0;

foreach(char letter in choice.ToCharArray) {

    if (letter == 'a')
        total += 500;

    // so on..
}

您似乎想要求用户输入多个选项,然后对这些选项进行一些操作。 您似乎也有与每个项目相关的价格/成本,所以我会考虑在这种情况下使用3-Tuple

var options = new List<Tuple<int, string, int>>
{
    Tuple.Create( 1, "Cake", 100 ),
    Tuple.Create( 2, "Milk", 200 ),
    Tuple.Create( 3, "Noodles", 300 ),
    Tuple.Create( 4, "Cheese", 400 ),
    Tuple.Create( 5, "Coke", 500 )
};

第一个是您希望用户输入的选项,第二个是项目名称,第三个是单价。

然后要求用户输入他们的选择,用逗号分隔:

Console.WriteLine("Select one or more options seperated by a comma");
foreach (var opt in options)
{
    Console.WriteLine("{0} - {1}", opt.Item2, opt.Item1);
}
var selection = Console.ReadLine();

接下来,我们将用逗号分割用户输入并遍历它们。 显然,如果你想要一个好的程序,你必须在这里进行错误处理,以防用户输入错误,但这只是为了说明。

var items = selection.Split(',');
foreach (var item in items)
{
    if (int.TryParse(item, out int value))
    {
        // We're looking in the 'options' list if we have the selection the user made
        var option = options.FirstOrDefault(x => x.Item1 == value);
        if (option != null)
        {
            // If it does exist, do what you want with it. Here I'm merely printing them.
            Console.WriteLine("{0} - {1} - {2}", option.Item1, option.Item2, option.Item3);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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