[英]Sum of the entries in the row of a 2D array within a java method
I am currently enrolled in an online java class and my problem is as follows:我目前注册了一个在线 java class 我的问题如下:
Write a method
addRow
which has two parameters: a 2D array of doubles and an int.编写一个方法
addRow
,它有两个参数:一个二维数组和一个 int。 Return the sum of the entries in the row given by the second parameter.返回第二个参数给出的行中条目的总和。 Return 0 if the row number is invalid.
如果行号无效,则返回 0。 Do not assume that the number of rows and columns are the same.
不要假设行数和列数相同。
My code for this question so far is as follows (I was only able to create the 2D array):到目前为止,我对这个问题的代码如下(我只能创建二维数组):
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*/
Firstly, your formed array is wrong as per your question.首先,根据您的问题,您形成的数组是错误的。 It mentions 2D array of
doubles
but you have chosen to define an 2D array of int
它提到了
doubles
的二维数组,但您选择定义一个int
的二维数组
Your table should look like the following rather.您的表格应该如下所示。
double table[][] = new double[4][5];
The question is pretty straightforward in itself.这个问题本身就很简单。 Create a function
addRow(double[][] array, int row)
创建一个 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.