向用户提交2D阵列

时间:2018-09-21 03:41:48

标签: c# arrays multidimensional-array console-application

            Console.WriteLine("\n\t\t\tTwo Dimensional Array");
            Console.Write("\nEnter the number of rows in the array : ");
            int row = Convert.ToInt32(Console.ReadLine());
            Console.Write("\nEnter the number of columns in the array : ");
            int column = Convert.ToInt32(Console.ReadLine());

            string[,] array1;
            array1 = new string[row,column];

            for(int i = 0; i < array1.Length; i++)
            {
                Console.Write("\nEnter the {0}th Row Element : ", i);
                array1[i, 0] = Console.ReadLine();

                for (int j = 0; j < array1.Length; j++)
                {
                    Console.Write("\t& {0}th Column Element : ", j);
                    array1[0,j] = Console.ReadLine();
                }
            }

            for (int i = 0; i < array1.Length; i++)
            {
                Console.Write("\nArray Element at {0}th Row is : {1}", i, array1[i,0]);
                for (int j = 0; j < array1.Length; j++)
                {
                    Console.Write("\t& the {0}th Column is : {1}",j,array1[0,j]);
                }
            }

            Console.ReadLine();

我希望在控制台中接受用户的以下建议: 1)排名(行数和列数) 2)数组的数据

我已经创建了上面的内容,但是,我收到异常错误,提示“索引超出范围”

犯了什么错误?

1 个答案:

答案 0 :(得分:0)

您需要每个dimension in the array using GetLength()的长度。

更改:

for(int i = 0; i < array1.Length; i++)

收件人:

for(int i = 0; i < array1.GetLength(0); i++)

并更改:

for(int j = 0; j < array1.Length; j++)

收件人:

for(int j = 0; j < array1.GetLength(1); j++)