【问题标题】:C# Using user input to select what string array to randomly print the elements fromC# 使用用户输入来选择从哪个字符串数组中随机打印元素
【发布时间】:2016-05-18 18:11:56
【问题描述】:

我是编码新手,所以请原谅我的术语..

我正在尝试制作一个随机的英雄联盟皮肤选择器。我希望用户输入他们想要的冠军,在这种情况下我有 ahri 和 leeSin,然后通过用户输入,我希望它选择字符串数组并随机打印其中一个元素。我想我已经很接近了,但我不能使用带有字符串 [] 的字符串。任何帮助将不胜感激。

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

        {
            string[] ahri = { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" };
            string[] leeSin = { "Traditional", "Acolyte", "Dragon Fist", "Musy Thai", "Pool Party", "SKT T1", "Knockout" };

            // Creates title for application
            Console.WriteLine("Conor's Random League of Legends Skin Selector v0.1");
            Console.WriteLine(" ");
            Console.WriteLine(" ");

            Random rnd = new Random();

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("What champion would you like to select a skin for?..    ");
            string champion = Console.ReadLine();

            foreach (string s in champion)
            {
                while (true)
                {
                    // Gets user to press a key to run the code
                    Console.Write("Press the 'enter' key for a random champion..     ");
                    string question = Console.ReadLine();

                    int randomNumber = rnd.Next(ahri.Length);
                    Console.WriteLine(ahri[randomNumber]);
                }
            }
        }
    }
}

【问题讨论】:

    标签: c# arrays string random


    【解决方案1】:

    一种方法是数组数组。看看https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx,特别是他们谈论Array-of-arrays(锯齿状)的地方。

    一种(可能)更直观的方法是数组字典。想一想:

    Dictionary<string, string[]> myList = new Dictionary<string, string[]>();
    myList.Add("ahri",new string[] { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" });
    //your other code
    Console.WriteLine(myList[champion][randomNumber]);
    

    考虑使用数组 myList[champion].Length 的长度作为随机数的界限,以避免出现越界错误。

    【讨论】:

    • 感谢您的建议!明天我会阅读它,如果我有任何问题,请告诉您。
    • @Conor 您提到您使用了 2 个以上的数组,这将是一个很好的解决方案,它将使代码非常简单。要添加的另一件事是避免在元素数组长度不同的情况下溢出的代码
    【解决方案2】:

    试一试:

        static void Main(string[] args)
            {
                Dictionary<string, string[]> skins = new Dictionary<string, string[]>();
                skins.Add("ahri", new string[] { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" });
                skins.Add("leesin", new string[] { "Traditional", "Acolyte", "Dragon Fist", "Musy Thai", "Pool Party", "SKT T1", "Knockout" });
    
                // Creates title for application
                Console.WriteLine("Conor's Random League of Legends Skin Selector v0.1\r\n\r\n");
    
                Random rnd = new Random();
    
                Console.ForegroundColor = ConsoleColor.Gray;
    
                Console.WriteLine("What champion would you like to select a skin for?..    ");
                string champion = Console.ReadLine().ToLower();
    
                Console.Write("Press the 'enter' key for a random champion..     ");
                Console.ReadLine();
                if(skins.ContainsKey(champion))
                {
                    //return a random champion skin from the user input key in dict based on a random number from the length of the string array
                    Console.WriteLine(skins[champion][rnd.Next(skins[champion].Length)]);
    
                }
    
            }
    

    添加到Dictionary 允许您通过检查冠军名称或Key 来简化流程,然后根据长度从string[] 数组或Value 中随机选择皮肤,这要归功于一个介于 0 和数组中元素计数之间的随机数。

    希望这有助于萌芽:)


    编辑:我有点无聊并玩弄了这个(无聊是指试图避免完成我的作业),所以我想出了一些对你更友好的东西。人们可能会讨厌我为您提供整个解决方案,但它向您展示了处理这些情况的方法,因此我将其视为以身作则。看看吧。

    static void Main(string[] args)
    {
        Console.Clear(); //For a 'clean slate' on every execution, can ditch this if you want
        Console.ForegroundColor = ConsoleColor.Gray;
    
        Dictionary<string, string[]> skins = new Dictionary<string, string[]>();
        skins.Add("ahri", new string[] { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" });
        skins.Add("leesin", new string[] { "Traditional", "Acolyte", "Dragon Fist", "Musy Thai", "Pool Party", "SKT T1", "Knockout" });
    
        Console.WriteLine("Conor's Random League of Legends Skin Selector v0.1\r\n\r\n");
        Console.WriteLine("What champion would you like to select a skin for? \r\nPress enter for a random champion...    ");
    
        var champion = Console.ReadLine(); 
        var rnd = new Random();
        if (champion.Equals(string.Empty))
        {
            var tmpList = Enumerable.ToList(skins.Keys);
            champion = tmpList[rnd.Next(tmpList.Count)];
        }
        else
        {
            champion = champion.Trim().ToLower(); 
        }
    
        Console.Write(string.Format("Champion {0} Selected \r\n", champion));
    
        if (skins.ContainsKey(champion)) 
        {
            Console.WriteLine(string.Format("Your random skin for {0} is: {1}\r\n", champion, skins[champion][rnd.Next(skins[champion].Length)]));
        }
        else
        {
            Console.Clear(); //clear the slate so console doesn't look cluttered.
            Main(args); 
        }
    }
    

    现在除了你在英雄和他们的皮肤中添加了 127 个奇怪的东西之外,这已经基本完成了。

    简明扼要,短小精悍。

    • 对处理所有用户输入的Console 进行一次调用,其余的都是自动化的
    • 检查一个空的string,如果它找到一个这是有效的并输入击键,就好像他们输入了一个不正确的值,它不会在Dict中找到,所以无论如何它都会“重新启动”程序。所以他们有两个选择:输入一个以string Key 表示的正确值,或者将其留空并按回车键。
    • 如果找到空的string(输入),它会将皮肤DictKeys 转换为List,并根据元素的0 和Count() 之间的随机数随机选择一个内说Dict
    • 否则,它将读取的输入转换为可用的字符串,然后继续
    • 检查调整后的用户输入或随机选择的string keyDictKeys 是否匹配,如果找到,则根据数组元素的LengthCount 输出随机皮肤在那个KeysValue下,此时程序存在。
    • 如果未找到 Key(仅基于错误的用户输入),则会清除控制台并“重新启动”应用程序。

    这远不是可用的最佳实现,但它确实有效,我真的看不出它的逻辑有问题,如果它在某个地方有问题,可以随时更新我。假设我现在应该做我的作业。这 15 分钟用得很好,很有趣。一定喜欢编码:)

    希望这会有所帮助,也许您现在可以研究一些东西并扩展您的知识。

    稍后

    【讨论】:

    • 非常感谢,这正是我要找的。我会确保阅读字典,以便我自己使用它们。
    • 没问题,乐于助人——祝你好运
    • @Conor 为你更新了一下,希望你能学到一些东西 :) 很无聊。祝你有个美好的一天:)
    • 哇,谢谢,没想到会有这么深入的回复:D 我肯定有一些研究要做,但这是一件好事。非常感谢。我今天晚些时候回家后会乱来。祝你的作业好运。
    【解决方案3】:

    试试这个:

    namespace RandomLolChampSelector
    {
        class Program
        {
            static void Main(string[] args)
    
            {
                string[] ahri = { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" };
                string[] leeSin = { "Traditional", "Acolyte", "Dragon Fist", "Musy Thai", "Pool Party", "SKT T1", "Knockout" };
    
                // Creates title for application
                Console.WriteLine("Conor's Random League of Legends Skin Selector v0.1");
                Console.WriteLine(" ");
                Console.WriteLine(" ");
    
                Random rnd = new Random();
    
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("What champion would you like to select a skin for?..    ");
                string champion = Console.ReadLine();
    
    
                        // Gets user to press a key to run the code
                 Console.Write("Press the 'enter' key for a random champion..     ");
                 string question = Console.ReadLine();
    
                 if(champion == "ahri")
                 {
                    int randomNumber = rnd.Next(ahri.Length-1);
                    Console.WriteLine(ahri[randomNumber]);
                 }
                 else //If you have more than 2 arrays you will need another if or a case statement
                 {
                    int randomNumber = rnd.Next(leeSin.Length-1);
                    Console.WriteLine(leeSin[randomNumber]);
                 }
            }
        }
    }
    

    【讨论】:

    • 这个问题是,我只做 2 个数组用于测试目的。我最终需要添加 127,所以使用这种方法效率非常低。不过感谢您的建议。
    • 很好地抓住了随机数 gen 的 Length-1!我同意,直接的 KISS (people.apache.org/~fhanik/kiss.html) 方法有利于可读性。从单例到 if/else if,再到 switch/case 都是泛化解决方案的所有步骤。
    • 测试后你不需要 -1 补偿,因为 Random.Next(maxValue) returns 0 to maxValue -1 msdn link 之前正在考虑它,这让我很烦。弄清楚我的猜测
    【解决方案4】:

    我已经修改了您的原始程序(尽可能多地保留您的代码)以产生预期的行为。请随时在此处按原样运行并研究我为使其工作所做的工作:

    class Program
    {
        static void Main(string[] args)
        {
            string[] ahri = { "Academy", "Challenger", "Dynasty", "Foxfire", "Midnight", "Popstar" };
            string[] leeSin = { "Traditional", "Acolyte", "Dragon Fist", "Musy Thai", "Pool Party", "SKT T1", "Knockout" };
    
            // Creates title for application
            Console.WriteLine("Conor's Random League of Legends Skin Selector v0.1");
            Console.WriteLine(" ");
            Console.WriteLine(" ");
    
            Random rnd = new Random();
    
            Console.ForegroundColor = ConsoleColor.Gray;
    
            // Stores what array has been selected:
            string[] champions;
    
            Console.WriteLine("What champion would you like to select a skin for?..    ");
            string championName = Console.ReadLine();
            if (championName.Equals("ahri", StringComparison.CurrentCultureIgnoreCase))
            {
                champions = ahri;
            }
            else if (championName.Equals("leeSin", StringComparison.CurrentCultureIgnoreCase))
            {
                champions = leeSin;
            }
            else 
            {
                // No champion selected, exit program:
                Console.WriteLine("No champion selected, quitting...");
                return;
            }
    
            while (true)
            {
                // Gets user to press a key to run the code
                Console.WriteLine("Press the 'enter' key for a random champion..     ");
                if (Console.ReadKey(true).Key == ConsoleKey.Enter)
                {                    
                    int randomNumber = rnd.Next(champions.Length);
                    Console.WriteLine(champions[randomNumber]);
                }
            }
        }
    }
    

    【讨论】:

    • 如果只有 2 个数组,这将起作用,但是,我计划添加 127+,所以这对我不起作用,因为它效率低下,不过还是谢谢。
    • 我明白了。同意,虽然这解决了您问题中的示例,但听起来您需要更多类似于 Gabe 提出的 Dictionary 方法的内容,如果您有这么多的收藏品可以满足。
    猜你喜欢
    • 2017-02-08
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2020-11-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多