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));