0

I'm writing a program so that it computes and prints the sum of each column of the array. The given data looks like this:

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

Ideally, it should output the results 13, 9, 15, 13, 12, -8. But since some of the rows have different lengths, when I run my program, it outputs 13, 9, 15 and gives me an ArrayIndexOutOfBoundsException. And I really don't know how to fix it.

Here is my code:

public class ColumnSums
{
public static void main(String[] args) {

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

    //Determine the number of data in the longest row
    int LongestRow = 0;
    for ( int row=0; row < data.length; row++){
        if ( data[row].length > LongestRow ){
            LongestRow = data[row].length;
        }
    }
    System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing

    //Save each row's length into a new array (columnTotal)
    int[] columnTotal = new int[4];

    //Scan through the original data again
    //Record each row's length into a new array (columnTotal)
    System.out.println("The lengths of each row are: ");
    for ( int i = 0; i < data.length; i++){
        columnTotal[i] = data[i].length;
        System.out.println(columnTotal[i]); //Testing
    }


    // Create an array to store all the sums of column
    int ColumnSums[] = new int[LongestRow];
    System.out.println("The sums of each column are: ");

    for ( int i = 0; i < LongestRow; i++ ){

            int sum = 0;

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

            ColumnSums[i] = sum;
            System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
    }


}
}

Thanks for your time!!!

Jessicaaa
  • 25
  • 1
  • 7
  • 1
    the trick here is to get the length of the specific row (what you should always do just in case). So the inner loop would look like `for (int j = 0; j < array[i].length; j++)` – AxelH May 05 '17 at 13:35
  • 1
    Look this post ["sums of columns in a 2 dimensional array"](http://stackoverflow.com/questions/14302971/sum-of-columns-in-a-2-dimensional-array) – thibsc May 05 '17 at 13:44
  • Possible duplicate of [how to sum the columns of a 2 dimensional array in java](http://stackoverflow.com/questions/12869878/how-to-sum-the-columns-of-a-2-dimensional-array-in-java) – Julio Betta May 05 '17 at 13:50
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – AxelH May 05 '17 at 13:54

3 Answers3

1

To read a 2D array your loops should be

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

See the use of for(int j = 0; j < array[i].length; ++j) to use the current row length.

With this, you will prevent this ArrayIndexOutOfBoundsException

I am open to question if you need. Just post a comment !

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • Aren't we supposed to provide a solution to calculate sum of columns? – Sanket Makani May 05 '17 at 13:42
  • 1
    First, I didn't notice, second, that's ok, I am not here to do the homework but to guide ;) So do you by the way ;) – AxelH May 05 '17 at 13:44
  • Yes but now do some modifications accordingly. :) – Sanket Makani May 05 '17 at 13:45
  • 1
    @SanketMakani No... SO is not suppose to provide code ready to use but to explain the problem... Just providing a solution would not help anyone (except me and my boredom...) I remove the code beacuse I found it to easy to write by the way – AxelH May 05 '17 at 13:46
1

You basically just need to loop through the columns until the counter is out of bounds for every row. No need to loop through ahead of time to find the longest row.

   public static ArrayList<Integer> getCollumnSum() {
        int[][] data = {{3, 2, 5},
                        {1, 4, 4, 8, 13},
                        {9, 1, 0, 2},
                        {0, 2, 6, 3, -1, -8}};
        int col = 0;
        ArrayList<Integer> totals = new ArrayList<Integer>();
        while (true) {
          int total = 0;
          boolean dataInCol = false;
          for (int i = 0; i < data.length; i++) {
            if (col < data[i].length) {
                total += data[i][col];
                dataInCol = true;
            }
          }
          col += 1;
          if (dataInCol) {
            totals.add(total);
          } else {
            break;
          }
        }
        return totals;
      }

Output:

[13, 9, 15, 13, 12, -8]
Alex S
  • 572
  • 7
  • 15
0

I have altered your code to fit your needs

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

int longestRow = 0;
for ( int row=0; row < data.length; row++){
    if ( data[row].length > longestRow ){
        longestRow = data[row].length;
    }
}
System.out.println("The longest row in the array contains " + longestRow + " values"); 

Here, no need for columnTotal as I can't notice any use of it. It maybe your program need. Anyway, you can print the length of each row directly as below.

System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
     System.out.println("Row " + i + " is " + data[i].length); 
    }

You can't get the sum of each column at each inner loop, because the sum of each column will be obtained after the both loops finish. Therefore, the variable sum is useless. So, it would be like below

int columnSums[] = new int[longestRow];
for ( int i = 0; i < data.length; i++ ){
        for (int j = 0; j < data[i].length; j++){
                columnSums[j] +=data[i][j];
            }
    }

Finally, you can print the sum of each column as below

System.out.println("The sums of each column are: ");

for (int i = 0; i < columnSums.length; i++) {
        System.out.println("Column " + i + ": " + columnSums[i]);
    }

After running the code, the output would be:

The longest row in the array contains 6 values
The lengths of each row are: 
Row 0 is 3
Row 1 is 5
Row 2 is 4
Row 3 is 6
The sums of each column are: 
Column 0: 13
Column 1: 9
Column 2: 15
Column 3: 13
Column 4: 12
Column 5: -8
FSm
  • 2,017
  • 7
  • 29
  • 55