Java-如何在二维数组中添加一行的总和 [英] Java- How to add sum of a row in 2d array

查看:26
本文介绍了Java-如何在二维数组中添加一行的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是将二维数组中每一行的总和相加,然后将这些值放入一个新的一维数组中.

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

这是我的代码

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.

推荐答案

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;
    }

您已经正确编写了大部分代码,但是您需要添加每一行,因此您需要添加 N[0][1], ....N[0][N[0].length - 1]在第 0 行.现在只需插入 i 和 j 值并写在纸上就清楚了.

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.

这篇关于Java-如何在二维数组中添加一行的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆