-2
我正在研究這個程序,我想在兩維數組中的每一行的最後一列中找到元素的總和。如何獲取二維數組中每行最後一列中元素的總和?
到目前爲止,我有這個代碼工作得很好。
public class Lab {
public static void main(String[] args) {
int[][] arr = { { 2, 4, 5, 7 }, { 4, 8, 7, 5 }, { 5, 9, 2, 20 } };
//getting each array from multidimensional array (arr)
int[] firstRow = arr[0];
int[] secondRow = arr[1];
int[] lastRow = arr[arr.length - 1];
//getting last element in each row
int lastItemInFirstRow = firstRow[firstRow.length - 1]; // 7
int lastItemInSecondRow = secondRow[secondRow.length - 1];// 5
int lastItemInLastRow = lastRow[lastRow.length - 1]; // 20
//sum of the elements in the last column of each row in a two-dimensional array
// 7 + 5 + 20
System.out.println(lastItemInFirstRow + lastItemInSecondRow + lastItemInLastRow); //32
}
}
但是,我需要創建一個更有效的方法。例如,如果我的多維數組中有20個數組,那該怎麼辦?如果我嘗試上面的代碼,它會佔用很多代碼行。所以我創建了一個方法來處理每行最後一列中元素的總和,但我不知道如何獲得實際總和。請有人幫助我。非常感謝!
這裏是我的方法:
public static int sumOfElementsInLastColumn(int[][] arr){
int sum = 0;
for(int row = 0 ; row < arr.length; row++){
for(int column = 0 ; column < arr[row].length ; column++){
sum += arr[row][arr.length];
}
}
return sum;
}
非常感謝您的幫助! – HenryDev