1 回答
TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個贊
當(dāng)你這樣做時int coluna [] = array[column];,你實(shí)際上得到的是一行,而不是列。例如:
這樣做array[1]會給你這個數(shù)組:
{1,-5,-2,2}
因此,這樣做array[3]會給你一個錯誤,因?yàn)闆]有第 4 行/第 4 個數(shù)組(因?yàn)閿?shù)組從 0 開始)。相反,您需要遍歷您的行(即行數(shù)為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
}
添加回答
舉報(bào)
