首页 > 解决方案 > 从用户处归档二维数组

问题描述

            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)数组的数据

我已经创建了上述内容,但是,出现异常错误,包括“索引超出范围”

犯了哪些错误?

标签: c#arraysmultidimensional-arrayconsole-application

解决方案


您需要使用 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++)

推荐阅读