2014-08-27 149 views
0

所以我試圖使用foreach循環值到一個二維數組。我知道代碼應該看起來像這樣。將值循環到具有foreach循環的二維數組中?

 int calc = 0; 
     int[,] userfields = new int[3,3]; 

     foreach (int userinput in userfields) 
     { 

      Console.Write("Number {0}: ", calc); 
      calc++; 
      userfields[] = Convert.ToInt32(Console.ReadLine()); 
     } 

這是盡我所能。我試過使用

userfields[calc,0] = Convert.ToInt32(Console.ReadLine()); 

但顯然這不適用於二維數組。我對C#相對較新,我正在努力學習,所以我非常感謝所有的答案。

在此先感謝!

+0

什麼輸出你想?你的問題有點不清楚。此外,該代碼不會編譯。 – 2014-08-27 09:29:45

+0

@ shree.pat18最後,我將把它作爲一個3x3表進行循環。 – Tatu 2014-08-27 09:32:48

回答

4

它是一個二維數組顧名思義它有二維。所以當你想分配一個值時你需要指定兩個索引。像:

// set second column of first row to value 2 
userfield[0,1] = 2; 

在這種情況下,可能你想有一個for循環:

for(int i = 0; i < userfield.GetLength(0); i++) 
{ 
    for(int j = 0; j < userfield.GetLength(1); j++) 
    { 
     //TODO: validate the user input before parsing the integer 
     userfields[i,j] = Convert.ToInt32(Console.ReadLine()); 
    } 
} 

欲瞭解更多信息,看看:

+0

工程就像一個魅力,謝謝你! – Tatu 2014-08-27 09:35:16

+1

@Tatu如果您發現此答案有幫助,請考慮upvoting和接受。這是在Stack Exchange上表達謝意的習慣方式,並且還告知社區,您感覺您的問題已得到滿意答覆。 – 2014-08-27 09:36:29

+0

@MichaelKjörling我知道,我還不能接受答案。我必須等待一段時間才能做到這一點。儘管我已經積極參與,我會接受我可以做到的答案! :) – Tatu 2014-08-27 09:38:28