As done here: C # Two-dimensional int array,Sum off all elements , but this time with jagged arrays. Getting:
System.IndexOutOfRangeException.
I am a beginner asking for help. This is my code:
public static int Sum(int[][] arr)
{
int total = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i][j];
}
}
return total;
}
static void Main(string[] args)
{
int[][] arr = new int[][]
{
new int [] {1},
new int [] {1,3,-5},
};
int total = Sum(arr);
Console.WriteLine();
Console.ReadKey();
}
In your inner loop do this instead:
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != null)
{
for (int j = 0; j < arr[i].Length; j++)
{
total += arr[i][j];
}
}
}
return total;
Because your lists aren't even you get the exception on arr.GetLength(1)
for the first dimension - it has no item at that place.
The if (arr[i] != null)
line is needed in the case the array would look something like:
int[][] arr = new int[][]
{
new int [] {1},
null,
new int [] {1,3,-5},
};
In this case, when we loop with i==1
and try to do arr[i].Length
(meaning arr[1].Length
we will recieve a NullReferenceException
.
And after you do the basics and get to Linq all your current Sum
method can be replaced with:
arr.SelectMany(item => item).Sum()
But it is good to start with the basics :)
Since you're using a jagged array the dimensions of that array aren't necessarily even. Have a look at the initialization code of that jagged array:
int[][] arr = new int[][] {
new int [] {1},
new int [] {1,3,-5},
};
So in the first dimension, there are two elements ( {1}
and {1, 3, -5}
). But the second dimension isn't of the same length. The first element has got only one element ( {1}
) whereas the second element's got 3 elements ( {1, 3, -5}
). That's why you're facing the IndexOutOfRangeException
.
To fix that, you'll have to adjust the inner loop to the number of elements for that dimension. You can do that like this:
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr[i].Length; j++) {
total += arr[i][j];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.