I am writing a program that will take a jagged array and print said jagged array. I used a foreach loop to attempt to print the array. Whenever I would go to run the program and see if the Jagged array will print it fails. I also tried just a for loop to print the array. Every time I would go to run the program I get System.IndexOutOfRange has been thrown. "Index was outside the bounds of the Array for my for loop. I tried commenting the loop out and it would do the same thing for when I tried to call the min and max method.
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]));
}
CodePudding user response:
You defined the max number of elements in the array as 9 (NUMBER_OF_CITIES) but you have 10 elements in your array (from miles[0] to miles[9]) which is why it went out of bounds. Change:
const int NUMBER_OF_CITIES = 9;
to
const int NUMBER_OF_CITIES = 10;
CodePudding user response:
The immediate cause of the problem is incorrect length of the array:
const int NUMBER_OF_CITIES = 9;
int[][] miles = new int[NUMBER_OF_CITIES][];
which means that miles
have items in 0..8
range; but you put a line out of range
// 9 is out of range
miles[9] = new int[9] { 186, 129, 231, 264, 25, 97, 194, 66, 82 };
In order to git rid of such errors, try to declare and initialize miles
in one go and let .net compute all the Length
for you:
// 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 },
};