2016-12-05 60 views
-1

我在創建一個隨機字母發生器時遇到了問題。任何人都可以將我指向正確的方向嗎?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]; 
      } 
     } 
    } 
} 
+0

這行生成錯誤? – Yaman

+1

你的代碼在'rng.Next(0,26;')中不能編譯(缺少''''''''''''''''''''''''''''''''''',所以不清楚是什麼原因導致了錯誤 - 但是錯誤應該清楚。你不能_implicitly_將'string'轉換爲'int'。你將字符串傳遞給數組索引器('Grid [actualRandomLetter,actualRandomLetter]')。我猜你只想要'Grid [i,j] = actualRandomLetter' –

+2

'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

回答

1

ActualRandomLeter是一個字符串,並使用一個字符串不能訪問在陣列中的元件的位置(即myArray的[「你好」])。如果你想填充您生成的隨機字母的排列,這將這樣的伎倆:

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; 

      } 
     } 
    } 
+0

謝謝!我設法讓它工作。 – Joseph

0

不知道,如果你要的1個字符的字符串一個5x5的網格,或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();