简体   繁体   中英

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:

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.

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

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)

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;
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM