Java- How to add sum of a row in 2d array [closed]

断了今生、忘了曾经 提交于 2019-12-02 18:35:07

问题


My problem is to add the sum of each row in a 2d array, and put those values in a new 1d array.

This is my code

public static int[] sumRow(int[][] N){
        int[] rowSum = new int[N.length];
        for(int i = 0; i<N.length;i++){
            for(int j = 0; j<N[i].length; j++){
                rowSum[i] = N[i][j] + N[i+1][j+1];
            }
        }

        return rowSum;
    }

But it is not working, please help.


回答1:


public static int[] sumRow(int[][] N){
        int[] rowSum = new int[N.length];
        for(int i = 0; i<N.length;i++){
              rowSum[i] = 0;  //<= initialize value
            for(int j = 0; j<N[i].length; j++){
                rowSum[i] += N[i][j];    //<= sum of row
            }
        }

        return rowSum;
    }

You have written most of the code right but you need to add each row so, you need to add N[0][1], ....N[0][N[0].length - 1] in row 0. Now just plug i and j values and write on paper to be much clear.




回答2:


Try this.

public static int[] sumRow(int[][] N) {
    return Stream.of(N)
        .mapToInt(a -> IntStream.of(a).sum())
        .toArray();
}


来源:https://stackoverflow.com/questions/35905584/java-how-to-add-sum-of-a-row-in-2d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!