Your external loop condition creates problems. Here is your loop: -
for (int i = 0; i < array[i].length; i++)
Now that i reaches the value 3 , you are trying to access array[3].length . This will throw an IndexOutOfBounds exception.
Since the size of each internal array is the same, you can change your loop to : -
for (int i = 0; i < array[0].length; i++)
Or, better yet, just store array[0].length in some variable before hand. But that will not make much difference.
I also suggest you use the best way to calculate the sum of the columns. Avoid repeating line by line first. Keep the iteration normal, probably like this: -
public double[] columnSum(double [][] array){ int size = array[0].length; // Replace it with the size of maximum length inner array double temp[] = new double[size]; for (int i = 0; i < array.length; i++){ for (int j = 0; j < array[i].length; j++){ temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`. } } System.out.println(Arrays.toString(temp)); return temp; // Note you are not using this return value in the calling method }
So you can see how your problem is very simplified. What I did, instead of assigning a value to an array, I added a new value to array[i][j] to the existing temp[j] value. So, gradually the value of array[i][j] for all i (rows) summed up in temp[j] . This way you do not need to use confusing iteration. So, just add the above code to your method and delete the old one.
This method will also work fine even if you have a jagged-array , i.e. internal arrays do not have the same size. But just remember to carefully size the temp array.
Also note that I used the Arrays.toString(temp) method to print the array.
source share