打印锯齿状数组

Printing Jagged Array

我正在编写一个程序,它将采用锯齿状数组并打印所述锯齿状数组。我使用 foreach 循环尝试打印数组。每当我转到 运行 程序并查看 Jagged 数组是否会打印时,它都会失败。我还尝试了一个 for 循环来打印数组。每次我去 运行 我得到的程序 System.IndexOutOfRange 都被抛出。 “对于我的 for 循环,索引超出了数组的范围。我尝试将循环注释掉,当我尝试调用 min 和 max 方法时它会做同样的事情。

    static void Main(string[] args)
        {
            const int NUMBER_OF_CITIES = 9;
            int i;
            int[][] miles = new int[NUMBER_OF_CITIES][];
            miles[0] = new int[1] { 0 };
            miles[1] = new int[1] { 290 };
            miles[2] = new int[2] { 373, 102 };
            miles[3] = new int[3] { 496, 185, 228 };
            miles[4] = new int[4] { 193, 110, 208, 257 };
            miles[5] = new int[5] { 214, 90, 165, 270, 73 };
            miles[6] = new int[6] { 412, 118, 150, 81, 191, 198 };
            miles[7] = new int[7] { 222, 86, 173, 285, 41, 34, 201 };
            miles[8] = new int[8] { 112, 207, 301, 360, 94, 155, 288, 141 };
            miles[9] = new int[9] { 186, 129, 231, 264, 25, 97, 194, 66, 82 };
            int index = 0;
            foreach (int[] milesRows in miles)
            {
                Console.Write("\t" + ++index);
                for (int j = 0;j < milesRows.Length; j++)
                {
                    Console.Write(milesRows[j] + "\t");
                }
                Console.WriteLine();
            }


            Min(miles[7]);
            Max(miles[7]);
            Console.WriteLine("The clossest is: " + Min(miles[7]));
            Console.WriteLine("The farthest is: " + Max(miles[7]));
        }

您将数组中元素的最大数量定义为 9 (NUMBER_OF_CITIES),但您的数组中有 10 个元素(从 miles[0] 到 miles[9]),这就是它消失的原因的界限。变化:

const int NUMBER_OF_CITIES = 9;

const int NUMBER_OF_CITIES = 10;

问题的直接原因是数组的长度不正确:

 const int NUMBER_OF_CITIES = 9;

 int[][] miles = new int[NUMBER_OF_CITIES][];

这意味着 miles0..8 范围内的项目;但是你放了一行超出范围

 // 9 is out of range
 miles[9] = new int[9] { 186, 129, 231, 264, 25, 97, 194, 66, 82 };

为了 git 消除此类错误,尝试在 中声明和初始化 miles 并让 .net 计算所有 Length 给你:

 // note, that we don't specify Length anywhere and let .net do it itself
 int[][] miles = new int[][] {
   new int[] { 0 },
   new int[] { 290 },
   new int[] { 373, 102 },
   new int[] { 496, 185, 228 },
   new int[] { 193, 110, 208, 257 },
   new int[] { 214, 90, 165, 270, 73 },
   new int[] { 412, 118, 150, 81, 191, 198 },
   new int[] { 222, 86, 173, 285, 41, 34, 201 },
   new int[] { 112, 207, 301, 360, 94, 155, 288, 141 },
   new int[] { 186, 129, 231, 264, 25, 97, 194, 66, 82 },
 };