0

I should create a method that print the sum of a given column in the main. This program shows a compilation error of:

Error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at algproo2.ALGPROO2.sumColumn(ALGPROO2.java:29)
at algproo2.ALGPROO2.main(ALGPROO2.java:24)

Java Result: 1

What should i do?

public class ALGPROO2 
{
    public static void main(String[] args)
    {
        int[][] a = {
            {-5,-2,-3,7},
            {1,-5,-2,2},
            {1,-2,3,-4}
        };
        System.out.println(sumColumn(a,1)); //should print -9
        System.out.println(sumColumn(a,3)); //should print 5
    }
    public static int sumColumn(int[][] array, int column)
    {
      int sumn = 0;
      int coluna [] = array[column];
      for (int value : coluna )
      {
        sumn += value;
      }
      return sumn; 
    }


}
Deadpool
  • 29,532
  • 9
  • 38
  • 73

1 Answers1

1

When you do int coluna [] = array[column]; you're actually getting one row, not the column. For example:

Doing array[1] would give you this array:

{1,-5,-2,2}

Thus, doing array[3] will give you an error as there is no 4th row / 4th array (as arrays start at 0). Instead, you need to loop over your rows (ie the number of rows is array.length). Then at each row, you can access the value at that particular column:

public static int sumColumn(int[][] array, int column) {
  int sumn = 0;
  for(int i = 0; i < array.length; i++) {
    int row[] = array[i]; // get the row
    int numFromCol = row[column]; // get the value at the column from the given row
    sumn += numFromCol; // add the value to the total sum

  } 
  return sumn; // return the sum
}
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44