我在創建一個隨機字母發生器時遇到了問題。任何人都可以將我指向正確的方向嗎?C#二維數組中的隨機字母生成器 - 問題
,我發現了錯誤
無法隱式轉換字符串爲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];
}
}
}
}
這行生成錯誤? – Yaman
你的代碼在'rng.Next(0,26;')中不能編譯(缺少''''''''''''''''''''''''''''''''''',所以不清楚是什麼原因導致了錯誤 - 但是錯誤應該清楚。你不能_implicitly_將'string'轉換爲'int'。你將字符串傳遞給數組索引器('Grid [actualRandomLetter,actualRandomLetter]')。我猜你只想要'Grid [i,j] = actualRandomLetter' –
'Grid [actualRandomLetter,actualRandomLetter];':這需要整數作爲索引,例如'Grid [0,3]'來檢索位於索引處的值'(0,3)',但是你傳入了例如'Grid [「A」,「A」]'這是沒有意義的。也不要多次構建一個新的Random(),只做一個然後多次調用'rng.Next';看到[這裏](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number/768001#768001)爲什麼。 – Quantic