[英]Sum of the entries in the row of a 2D array within a java method
我目前注冊了一個在線 java class 我的問題如下:
編寫一個方法
addRow
,它有兩個參數:一個二維數組和一個 int。 返回第二個參數給出的行中條目的總和。 如果行號無效,則返回 0。 不要假設行數和列數相同。
到目前為止,我對這個問題的代碼如下(我只能創建二維數組):
int table[][] = new int[4][5];
table[0][0] = 0;
table[0][1] = 1;
table[0][2] = 2;
table[0][3] = 3;
table[0][4] = 4;
table[1][0] = 1;
table[1][1] = 2;
table[1][2] = 3;
table[1][3] = 4;
table[1][4] = 5;
table[2][0] = 1;
table[2][1] = 2;
table[2][2] = 3;
table[2][3] = 4;
table[2][4] = 5;
/*System.out.println table*/
首先,根據您的問題,您形成的數組是錯誤的。 它提到了doubles
的二維數組,但您選擇定義一個int
的二維數組
您的表格應該如下所示。
double table[][] = new double[4][5];
這個問題本身就很簡單。 創建一個 function addRow addRow(double[][] array, int row)
public static double addRow(double[][] array, int row) {
double sum = 0.0;
// check for valid input as row number
if (row < array.length) {
// iterate over all columns/cells of that row
for (int i = 0; i < array[row].length; i++) {
sum = sum + array[row][i];
}
}
return sum;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.