How to fix ArrayIndexOutOfBoundsException for 2D array
I am starting to program in Java and am just writing a simple program to return the sum of the elements in the i-th column of a two-dimensional array.
But one of my tests gave me an ArrayIndexOutOfBoundsException error which is shown below:
Test case with problem:
int[][] numbers3 = {{3}, {2, 4, 6}, {3, 6}, {3, 6, 9, 12}};
System.out.println(columnSum(3, numbers3));
This is the error message I got from this test case:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Array.columnSum(Array.java:12)
at Array.start(Array.java:6)
at ArrayApp.main(ArrayApp.java:7)
I don't know how to fix this problem ... so can someone please point out my mistake please? Thank!
Here's my code:
public class Array {
public void start() {
int[][] numbers3 = {{3}, {2, 4, 6}, {3, 6}, {3, 6, 9, 12}};
System.out.println(columnSum(3, numbers3));
}
private int columnSum(int i, int[][] nums) {
int sum = 0;
for(int row = 0; row < nums.length; row++){
sum = sum + nums[row][i];
}
return sum;
}
}
Here are some test cases I've used that work fine.
Test case 1:
int[][] nums = {{0, 1, 2, 3}, {2, 4, 6, 8}, {3, 6, 9, 12}};
System.out.println(columnSum(0, nums));
Test case 2:
int[][] nums2 = {{0, 1, 2, 3}, {2, 4, 6, 8}, {3, 6, 9, 12}};
System.out.println(columnSum(3, nums2));
source to share
Looking at your array
int[][] numbers3 = {{3}, {2, 4, 6}, {3, 6}, {3, 6, 9, 12}};
numbers3 [0] is only {3}, the size of the array is 1. Thus, calling numbers [3] [x], where x is something other than 0., throws an error, since it only has this item.
You have two options:
-
Use only arrays with the same number of elements.
int[][] numbers3 = {{3,1,3}, {2, 4, 6}, {3, 6,5}, {3, 6, 9}};
-
Add check and skip 0 instead
if(nums[row].length > i) sum = sum + nums[row][i];
This way, it never tries to check for an invalid index nums[row]
.
source to share
This is because in this example the column lengths are different, so the third column does not exist.
private static int columnSum(int i, int[][] nums) {
int sum = 0;
for(int row = 0; row < nums.length; row++){
if (i < nums[row].length) {
sum = sum + nums[row][i];
}
}
return sum;
}
source to share