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

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

最佳答案

一种方法是数组的数组。看看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[cham​​pion].Length 的长度作为随机数的边界,以避免出现越界错误。

关于C# 使用用户输入来选择要从中随机打印元素的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280531/

相关文章:

c# - 如何使用 C# 以编程方式从 azure B2C Active Directory 中删除用户

javascript - 使用JQuery实时大写用户输入的第一个字符

javascript - Javascript 中具有非数字索引的多维数组

javascript - 根据重复的字典属性将一维列表减少为锯齿状二维列表

javascript - 传递带有嵌套函数的函数和带有 array.map 的当前值

c++ - 将 basic_string<unsigned char> 转换为 basic_string<char> ,反之亦然

Java 显示正确 错误

C# 自定义序列化/反序列化以及 DeflateStreams

c# - Azure 流分析自定义 dll

c# - Azure IoT 中心中的 TCP 支持