如何编写一个方法来返回数组中给定列的总和?爪哇

时间:2019-02-25 03:06:51

标签: java arrays methods

我应该创建一个在主列中打印给定列总和的方法。该程序显示以下编译错误:

错误

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

Java结果:1

我该怎么办?

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; 
    }


}

1 个答案:

答案 0 :(得分:1)

当您执行int coluna [] = array[column];时,实际上是一行,而不是该列。例如:

array[1]会给你这个数组:

{1,-5,-2,2}

因此,执行array[3]会给您一个错误,因为没有第4行/第4个数组(因为数组从0开始)。相反,您需要遍历行(即行数为array.length)。然后,您可以在每一行访问该特定列的值:

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
}