如何编写返回数组中给定列的和的方法?JAVA

如何编写返回数组中给定列的和的方法?JAVA,java,arrays,methods,Java,Arrays,Methods,我应该创建一个方法,在main中打印给定列的和。此程序显示以下编译错误: 错误 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} }; Syste

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

错误

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


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

执行数组[1]将得到以下数组:

{1,-5,-2,2}
因此,执行数组[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
}

数组是基于零索引的。a的最后一个索引是:谢谢你的深入回复,尼克!那对我有用!:
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
}