【发布时间】: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。 -
谢谢。我已经移动了“随机”。尽管如此,仍然坚持填充数组。