我應該創建一個打印主列中給定列的總和的方法。該程序顯示以下編譯錯誤:錯誤Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3at 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 回答

繁星點點滴滴
TA貢獻1803條經驗 獲得超3個贊
當你這樣做時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
}
添加回答
舉報
0/150
提交
取消