Java 2D array: summing columns and displaying array problems -
when column count , row count same, code works fine. when differ throws exception inside columnsum
method.
here's error message.
exception in thread "main" java.lang.arrayindexoutofboundsexception:
and here's code
public static void columnsum(int[][] anarray) { int sum = 0; (int col = 0; col < anarray.length; col++) { (int r = 0; r < anarray[col].length; r++) { sum += anarray[r][col]; } system.out.println("sum of column " + col + " = " + sum); } system.out.println(); }
i have no idea why code doesn't work when have more columns rows or vice versa.
does have idea?
change sum += anarray[r][col]
to sum += anarray[col][r]
this reason why runs when columns & rows of same size. when they're of different length, instance 5 cols & 3 rows, code try access anarray[3][5] in 1 of iterations , elements not exist, hence exception.
Comments
Post a Comment