0

所以我正在尝试使用 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# 比较陌生,我正在努力学习,所以我很感激所有的答案。

提前致谢!

4

1 回答 1

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());
    }
}

有关更多信息,请查看:

于 2014-08-27T09:32:15.217 回答