Reputation: 443
I am a beginner in Java programming and I just writing a simple program to return the sum of elements in the i-th column of the two-dimensional array.
But one of my test case gave me an ArrayIndexOutOfBoundsException error, which show as below:
The test case with issue occurred:
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 solve this problem...so could anyone please point out my mistake please ? Thank you !
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's some test cases I used which is working 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));
Upvotes: 3
Views: 832
Reputation: 931
Looking at your array
int[][] numbers3 = {{3}, {2, 4, 6}, {3, 6}, {3, 6, 9, 12}};
numbers3[0] is only {3}, which is an array size of 1. Thus, calling numbers[3][x] where x is anything other than 0. will throw an error since it only has that element.
You have two options:
Only use arrays with the same number of elements.
int[][] numbers3 = {{3,1,3}, {2, 4, 6}, {3, 6,5}, {3, 6, 9}};
Add a check and pass in 0 instead
if(nums[row].length > i)
sum = sum + nums[row][i];
This way, it never attempts to check the invalid index of nums[row]
.
Upvotes: 6
Reputation: 2084
It's happening because your column lengths are different in that example so the third column doesn't 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;
}
Upvotes: 1