【问题标题】:C# Random Letter Generator into 2D array - ProblemsC# 随机字母生成器转换为二维数组 - 问题
【发布时间】:2016-12-05 23:13:30
【问题描述】:

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

我收到了错误

无法将字符串隐式转换为 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];
            }
        }
    }
}

【问题讨论】:

  • 哪一行产生了错误?
  • 您的代码无法编译(在rng.Next(0, 26; 中缺少)),因此不清楚是什么导致了错误 - 但错误应该很清楚。您不能隐式string 转换为int。您正在将字符串传递给数组索引器 (Grid[actualRandomLetter,actualRandomLetter])。我怀疑你只是想要Grid[i, j] = actualRandomLetter
  • Grid[actualRandomLetter,actualRandomLetter];:这需要索引的整数,例如Grid[0,3] 来检索位于索引(0,3) 的值,但是您传入的是例如Grid["A", "A"],这不会感觉。也不要多次构造new Random(),只创建一个然后多次调用rng.Next;请参阅here 了解原因。
  • 顺便说一句,不要为每个随机数创建新的Random。整个过程使用一个Random
  • 谢谢。我已经移动了“随机”。尽管如此,仍然坚持填充数组。

标签: c# arrays random


【解决方案1】:

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

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;

            }
        }
    }

【讨论】:

    【解决方案2】:

    不确定您是想要一个 5x5 的 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2014-12-15
      相关资源
      最近更新 更多