简体   繁体   中英

How do I sum a column if the rows and columns are not equal?

so I've gone on a few other summing columns in 2d arrays, but all of them have equal lengths whereas my does not. I have summed the rows (pretty straight forward), however, when I try to sum the column, it stops because there's not a number in the first row. How do I make it so it continues? I have included what the output is.

 import java.util.*;
 import java.io.*;



 public class Main
   {
      public static void main(String args[])
   { 
      int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };

       // declare the sum
       int sum;
       int sum2 = 0;

       // compute the sums for each row
       for ( int row=0; row < data.length; row++)
       {
       // initialize the sum, i did it to zero
       sum = 0;


       // compute the sum for this row
       for ( int col=0; col < data[row].length; col++) 
       {
           sum+=data[row][col];
       }

       // write the sum for this row
       System.out.println("The sum of this row is: " + sum);
   }

       for(int i = 0; i < data[0].length; i++)
        {  
          sum2= 0;  
          for(int j = 0; j < data.length; j++)
          {  
            sum2 = sum2 + data[j][i];  
          }   
          System.out.println("Sum of " + (i+1) +" column: " + sum2);  
        }
   }
}





/*Sample Output:
The sum of this row is: 10
The sum of this row is: 30
The sum of this row is: 12
The sum of this row is: 2
Sum of 1 column: 13
Sum of 2 column: 9
Sum of 3 column: 15
*/

Thank you to everyone!

Try this. The trick is to fill in the empty columns with zeroes as placeholders:

int[][] data = { {3, 2, 5},
                 {1, 4, 4, 8, 13},
                 {9, 1, 0, 2},
                 {0, 2, 6, 3, -1, -8} };

int length = 0;
for (int r = 0; r < data.length; r++) {
    int currLength = data[r].length;
    if(currLength>length) length = currLength;
}
// create array for column sums
int[] sums = new int[length];
// fill array with zeros
Arrays.fill(sums, 0);
// sum up
for (int currentRow = 0; currentRow < data.length; currentRow++) {
   for (int col = 0; col < data[currentRow].length; col++) {
       sums[col] += data[currentRow][col];
   } 
}   
// print sums
for (int i = 0; i < sums.length; i++) {
    System.out.println("Sum of column " + (i+1) + ": " + sums[i]);
}

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