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

Categories

I have two dimensional array as below:

[33] [96] [34] [11] [65] [68] [12] [8 ] [=327]

[94] [91] [3 ] [20] [16] [59] [74] [97] [=454]

[29] [0 ] [31] [13] [4 ] [63] [52] [73] [=265]

[51] [3 ] [55] [74] [52] [79] [61] [74] [=449]

[18] [19] [1 ] [53] [33] [93] [26] [14] [=257]

[56] [41] [4 ] [16] [45] [8 ] [57] [22] [=249]

[43] [33] [43] [59] [61] [58] [58] [69] [=424]

[38] [41] [42] [29] [27] [72] [85] [75] [=409]

[36] [3 ] [23] [65] [40] [56] [41] [96] [=36]

[=?] [=?] [=?] [=?] [=?] [=?] [=?] [=?]

how to get the sum of the columns in the array?

here is my code to get the sum of the rows:

public static void main(String[] args) {
    int[][] nums = new int[9][9];
    int random, total_rows=0, total_cols=0;
    Random randomGenerator = new Random();

    for (int i=0; i < 9; i++) {
        for (int j=0; j < 9; j++) {
            random = randomGenerator.nextInt(100);
            nums[i][j] = random;

            if(j < 8) {
                total_rows += random;
            }else {
                System.out.print("=");
                nums[i][j] = total_rows;
                total_rows = 0;
            }

            System.out.print(nums[i][j] + " ");
        }

        System.out.println();
    }
}
See Question&Answers more detail:os

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

1 Answer

You can try:

int[][] num = new int[9][9];
/*
 * ...populate the array
 *
 */
for (int i = 0; i < num.length; i++) {
    int sum = 0;
    for (int j = 0; j < num[i].length; j++) {
        sum += num[j][i];
    }
    System.out.println(sum);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...