1

I'm trying to compute the row and column sums of a 2D array but I'm always getting this error java.lang.ArrayIndexOutOfBoundsException: 2

It says there is a error in method computeRowSums but I cannot figure out why it would be array index out of bounds.

// RowColSums.java
// To compute the row and column sums of a 2D array.
import java.util.*;

public class RowColSums {

    public static void main(String[] args) {

        int row_size, col_size, row, col;
        int[][] array2D;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter number of rows and columns: ");
        row_size = sc.nextInt();
        col_size = sc.nextInt();

        array2D = new int[row_size][col_size];

        System.out.println("Enter values for 2D array: ");
        for(row = 0; row < row_size; row++)
            for(col = 0; col < col_size; col++)
                array2D[row][col] = sc.nextInt();

        int[] rowSums = computeRowSums(array2D);
        System.out.print("Row sums: ");
        System.out.println(Arrays.toString(rowSums));

        int[] colSums = computeColSums(array2D);
        System.out.print("Column sums: ");
        System.out.println(Arrays.toString(colSums));
    }

    public static int[] computeRowSums(int[][] arr)
    {
        int i, j; 
        int[] row_sum = new int[arr[0].length];

        for(i = 0; i < arr[0].length; i++) 
            for(j = 0; j < arr.length; j++)
                row_sum[i] += arr[i][j];

        return row_sum;

    }
    public static int[] computeColSums(int[][] arr)
    {
        int z, r;
        int[] col_sum = new int[arr.length];

        for(z = 0; z < arr.length; z++)
            for(r = 0; r < arr[0].length; r++)
                col_sum[z] += arr[z][r];

        return col_sum;
    }
}

1 Answers1

0

In computeRowSums you got the indices in the wrong order. It should be :

    for(i = 0; i < arr[0].length; i++) 
        for(j = 0; j < arr.length; j++)
            row_sum[i] += arr[j][i];

I'm assuming your 2D array has a different number of rows and columns, which explains the exception you got.

Eran
  • 387,369
  • 54
  • 702
  • 768