sum of columns in a 2 dimensional array

2020-02-11 07:57发布

问题:

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};

public double[] columnSum(double [][] array){
    int index = 0;
    double temp[] = new double[array[index].length];

    for (int i = 0; i < array[i].length; i++){
        double sum = 0;

        for (int j = 0; j < array.length; j++){
            sum += array[j][i];

        }
        temp[index] = sum;
        System.out.println("Index is: " + index + " Sum is: "+sum);
        index++;

    }

    return temp;
}


public static void main(String[] args) {
    arrayq test = new arrayq();
    test.columnSum(initialArray);

}

I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:

Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)

回答1:

Your outer for loop condition is giving you problems. Here's your loop: -

for (int i = 0; i < array[i].length; i++)

Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.


Since the size of every internal arrays are same, you can change your loop to: -

for (int i = 0; i < array[0].length; i++)

Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.


I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -

public double[] columnSum(double [][] array){

    int size = array[0].length; // Replace it with the size of maximum length inner array
    double temp[] = new double[size];

    for (int i = 0; i < array.length; i++){
        for (int j = 0; j < array[i].length; j++){
            temp[j] += array[i][j];  // Note that, I am adding to `temp[j]`.
        }
    }

    System.out.println(Arrays.toString(temp));
    return temp;  // Note you are not using this return value in the calling method
}

So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.

This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.

Also note that, I have used Arrays.toString(temp) method to print the array.



回答2:

Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.

int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
            int sum = 0;
            for(int i = 0; i < rows; i++)
            {
                sum = sum + input[i][j];
            }

        }


回答3:

for (int i = 0; i < array[i].length; i++)

for(int i=0;i<size;i++)

i & size must never be change in the loop



回答4:

So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.

You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.

for (int i = 0, j = 0; i < initialArray[j].length; i++) {
  for (; j < initialArray.length; j++) {
    System.out.println(i + " " + j);
  }
  j = 0;
}

And here is your modified program.

public class Main {
  static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };

  public double[] columnSum(double[][] array) {
    int index = 0;
    double temp[] = new double[array[index].length];
    for (int i = 0; i < array[0].length; i++) {
      double sum = 0;
      for (int j = 0; j < array.length; j++) {
        sum += array[j][i];
      }
      temp[index] = sum;
      System.out.println("Index is: " + index + " Sum is: " + sum);
      index++;
    }
    return temp;
  }

  public static void main(String[] args) {
    new Main().columnSum(initialArray);
  }
}


回答5:

for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression

try it

public double[] columnSum(double [][] array){
    double temp[] = new double[array[0].length];

    for (int i = 0; i < array[0].length; i++){
        double sum = 0;

        for (int j = 0; j < array.length; j++){
            sum += array[j][i];

        }
        temp[i] = sum;
        System.out.println("Index is: " + i + " Sum is: "+sum);

    }

    return temp;
}


标签: java arrays add