有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java方法中2D数组行中的项之和

我目前参加了一个在线java课程,我的问题如下:

Write a method addRow which has two parameters: a 2D array of doubles and an int. Return the sum of the entries in the row given by the second parameter. Return 0 if the row number is invalid. Do not assume that the number of rows and columns are the same.

到目前为止,我对这个问题的代码如下(我只能创建2D数组):

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*/

共 (1) 个答案

  1. # 1 楼答案

    首先,根据您的问题,您形成的数组是错误的。它提到了doubles的2D数组,但您选择了定义int的2D数组

    你的桌子应该像下面这样

    double table[][] = new double[4][5];
    
    

    这个问题本身就很简单。创建函数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;
    }