arraysmultidimensional-arrayjagged-arrays

Sum Specified Column Jagged Array


My homework assignment is asking to output the sum of a specified column of a Jagged 2D Array. I've seen other solutions that show how to get the sum of ALL columns, but not a specific one. The issue I'm running into is that I get a java.lang.ArrayIndexOutOfBoundsException if a column is entered and no element exists in a row of the 2D array.

// returns sum of specified column 'col' of 2D jagged array
public static int columnSum(int[][] array, int col) {
    int sum = 0;

// for loop traverses through array and adds together only items in a specified column
    for (int j = 0; j < array[col].length; j++) {
    sum += array[j][col];
    }

return sum;
} // end columnSum()

Example: Ragged Array Input (class is named RaggedArray)

int[][] ragArray = { {1,2,3}, 
                     {4,5}, 
                     {6,7,8,9} };

System.out.println(RaggedArray.columnSum(ragArray, 2));

This obviously gives me an ArrayIndexOutOfBoundsException, but I don't know how to fix it if a specified column is asked for as an argument. Any ideas? I appreciate any help or suggestions!


Solution

  • Here is another solution I found.

    // returns sum of the column 'col' of array
        public static int columnSum(int[][] array, int col) {
        int sum = 0;
    
        // for loop traverses through array and adds together only items in a specified column
        try {
            for (int j = 0; j < array.length; j++) {
                if (col < array[j].length)
                    sum += array[j][col];   
               }
            }
        catch (ArrayIndexOutOfBoundsException e){
            }
    
        return sum;
    } // end columnSum()