二维数组中列的总和,Java

Sum of the column in 2D Array, Java

我试图对每一列求和,但我没有得到预期的输出,正如你所看到的,我像普通(行和列)一样采用了这个二维数组的元素,但是对于 For 循环,我循环了先列后循环行。

输入;

3
4
1 2 3 4
4 5 6 5
7 8 9 5

预计输出;

12
15
18
14

我的输出;

6
13
18
22

我的代码;

import java.util.Scanner;
    public class exercise2_2darray {
        public static void main(String[] args) {
            
            Scanner sc=new Scanner(System.in);   
            int m = sc.nextInt();  //take input row 
            int n = sc.nextInt();  //take input col 
            int array[][] = new int[m][n];      
            
            for(int col =0; col<n; col++) { 
                  int Sum = 0; 
                  
                for (int row=0;row<m; row++) {
                        
                    array[row][col] = sc.nextInt();     
                    Sum+=array[row][col];               
                }           
                System.out.println(Sum);            
            }   
        }
    }

正确答案是将获取用户输入的for循环和数组求和循环分开;

import java.util.Scanner;
public class exercise2_2darray {
    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);   
        int m = sc.nextInt();  //take input row 
        int n = sc.nextInt();  //take input col 
        int array[][] = new int[m][n];      
        
        for(int row =0; row<m; row++) { 
                  
            for (int col=0;col<n; col++) {
                    
                array[row][col] = sc.nextInt();                         
            }                               
        }
        
        for(int col =0; col<n; col++) { 
              int Sum = 0; 
              
            for (int row=0;row<m; row++) {
                        
                Sum+=array[row][col];               
            }           
            System.out.println(Sum);            
        }   
        
    }
}

您输入的方式有误。你有切换行和列,结果你的输入是这样的。

1  4  6  8
2  4  5  9
3  5  7  5

总和为

6  13  18  22

要么您必须更改输入方式

1  4  7
2  5  8
3  6  9
4  5  5

或将 row 和 col 切换回通常(行作为外循环,列作为内循环)以获取输入并在另一个循环中分别执行 sum

for(int row=0; row<r; row++) {
    for(int col=0; col<n; col++) {
        ....// take input
    }
}
for(int row=0; row<r; row++) {
    int sum=0;
    for(int col=0; col<n; col++) {
        Sum+=array[row][col];
    }
    System.out.println(Sum);
}