C#使用用户输入选择要从中随机打印元素的字符串数组

时间:2016-02-08 22:25:24

标签: c# arrays string random

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

我试图制作一个随机的传奇皮肤选择器联盟。我希望用户输入他们想要的冠军,在这种情况下我有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]);
                }
            }
        }
    }
}

4 个答案:

答案 0 :(得分:4)

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

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

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的长度作为随机数的边界,以防止出现越界错误。

答案 1 :(得分: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 :(得分:3)

试一试:

    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[]数组或{{1}中随机选择皮肤由于0和数组中元素计数之间的随机数,基于它的长度。

。}

希望这有助于萌芽:)

编辑:我感到无聊并且玩了一下(感到无聊,我的意思是试图避免去做我的作业)所以我想出了一些对你更友好的东西。人们可能会因为给你整个解决方案而讨厌我,但它会告诉你如何处理这些情况,所以我把它看作是一个例子。看看。

Value

现在这几乎是完整的,除了你在冠军和他们的皮肤中增加了127个奇数。

快速破旧,简短而甜蜜。

  • 只需一次调用处理所有用户输入的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); } } ,其余就是自动
  • 检查空Console是否有效,并输入击键,就好像输入的值不正确一样,在string中找不到,所以它会'重启'程序无论如何。因此,他们有两个选项:输入一个表示为Dict string的正确值,或将其留空并按Enter键。
  • 如果找到并清空Key(输入),则会将皮肤string的{​​{1}}转换为Keys并根据0之间的随机数随机选择一个以及Dict
  • 中所有元素的List
  • 否则它会将读取输入转换为可用字符串,并在此处移动
  • 根据Count()检查调整后的用户输入或随机选择的Dict string是否key,根据{{1}输出随机皮肤{/ 1}} Keys下的数组元素或Dict,此时程序存在。
  • 如果找不到Length(仅基于错误的用户输入),则会清除控制台并“重启”应用程序。

这远不是可用的最佳实现,但它可以工作,我不能真正看到它的逻辑问题,如果它在某个地方有问题,可以随时更新我。假设我现在应该完成我的作业。这是15分钟,花了很多,很有趣。喜欢编码:)。

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

后来

答案 3 :(得分:1)

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

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