Sum Specified Column Jagged Array -
my homework assignment asking output sum of specified column of jagged 2d array. i've seen other solutions show how sum of columns, not specific one. issue i'm running java.lang.arrayindexoutofboundsexception if column entered , no element exists in row of 2d array.
// returns sum of specified column 'col' of 2d jagged array public static int columnsum(int[][] array, int col) { int sum = 0; // loop traverses through array , adds items in specified column (int j = 0; j < array[col].length; j++) { sum += array[j][col]; } return sum; } // end columnsum()
example: ragged array input (class named raggedarray)
int[][] ragarray = { {1,2,3}, {4,5}, {6,7,8,9} }; system.out.println(raggedarray.columnsum(ragarray, 2));
this gives me arrayindexoutofboundsexception, don't know how fix if specified column asked argument. ideas? appreciate or suggestions!
in loop, a
try{ sum += array[j][col]; }catch(arrayindexoutofboundsexception e){ }
block, skips on if there nothing, , keeps going next one. have import exception well. if run trouble, how try/catch blocks work
Comments
Post a Comment