Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - Adding up all the elements of each column in a 2D array

So I have this dummy 2D array:

int mat[][] = {
        {10, 20, 30, 40, 50, 60, 70, 80, 90},
        {15, 25, 35, 45},
        {27, 29, 37, 48},
        {32, 33, 39, 50, 51, 89}};

I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:

public void sum(int[][] array) {
    int count = 0;
    for (int rows = 0; rows < array.length; rows++) {
        for (int columns = 0; columns < array[rows].length; columns++) {
            System.out.print(array[rows][columns] + "");
            count += array[0][0];
        }
        System.out.println();
        System.out.println("total = " + count);
    }
}

Can anyone help with this? Also the System.out.print(array[rows][columns] + "" ); prints the array out by rows, is there a way to print it out by columns?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use an ArrayList to get the sum of all the columns.

public static void sum(int[][] array) {
    ArrayList<Integer> sums = new ArrayList<>();
    for (int row = 0; row < array.length; row++) {
        for (int column = 0; column < array[row].length; column++) {
            if (sums.size() <= column) {
                sums.add(column, 0);
            }
            int curVal = sums.get(column);
            sums.remove(column);
            sums.add(column, curVal + array[row][column]);
        }
    }
    for (int i = 0; i < sums.size(); i++) {
        System.out.println("Sum of column " + i + " = " + sums.get(i));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...