C#随机字母生成器到二维阵列 - 问题

时间:2016-12-05 23:13:30

标签: c# arrays random

我在创建随机字母生成器时遇到问题。有人能指出我正确的方向吗?

我收到了错误

  

无法将字符串隐式转换为int。

class Program
{
    static void Main(string[] args)
    {
        string[,] Grid = new string[5,5];

        string[] randomLetter = new string[26] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        for (int i = 0; i < Grid.GetLength(0); i++)
        {
            for (int j = 0; j < Grid.GetLength(1); j++)
            {
                Random rng = new Random();
                int nextRandom = rng.Next(0, 26;
                string actualRandomLetter = randomLetter[nextRandom];
                Grid[i, j] = Grid[actualRandomLetter,actualRandomLetter];
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

ActualRandomLeter是一个字符串,您无法使用字符串访问数组中元素的位置(即myArray [&#34; Hello&#34;])。如果您尝试使用您生成的随机字母填充数组,则可以解决这个问题:

public static void Main(string[] args)
    {
        string[,] Grid = new string[5, 5];
        string[] randomLetter = new string[26] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        Random rng = new Random();

        for (int i = 0; i < Grid.GetLength(0); i++)
        {
            for (int j = 0; j < Grid.GetLength(1); j++)
            {                 
                int nextRandom = rng.Next(0, 26);

                string actualRandomLetter = randomLetter[nextRandom];

                Grid[i, j] = actualRandomLetter;

            }
        }
    }

答案 1 :(得分:0)

不确定您是想要5个5字符的1个字符的字符串,还是5个字符串的数组,每个字符串包含5个字符。这些之间没有太大区别,因为两者都允许你grid[i][j]来获取第i行中的第j个字符。

这是一个有效的例子:

// We'll output an array with 5 elements, each a 5-character string.
var gridSize = 5; 
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var rand = new Random();
var grid = Enumerable.Range(0, gridSize)
    .Select(c=>new String(
        Enumerable.Range(0, gridSize)
        .Select(d=>alphabet[rand.Next(0, alphabet.Length)])
        .ToArray()
    )).ToArray();