将值循环到具有foreach循环的二维数组中?
问题描述:
所以我试图使用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#相对较新,我正在努力学习,所以我非常感谢所有的答案。
在此先感谢!
答
它是一个二维数组顾名思义它有二维。所以当你想分配一个值时你需要指定两个索引。像:
// 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());
}
}
欲了解更多信息,看看:
什么输出你想?你的问题有点不清楚。此外,该代码不会编译。 – 2014-08-27 09:29:45
@ shree.pat18最后,我将把它作为一个3x3表进行循环。 – Tatu 2014-08-27 09:32:48