JAVA如何计算二维数组中每一行的总和?

时间:2018-03-21 12:37:23

标签: java arrays arraylist multidimensional-array

我正在编写一些代码来计算数组中每行的总和。

    public static int sum(int[][] array) {
    int total = 0;
    for (int i = 0; i < array.length; i++) {
        for (int k = 0; k < array[i].length; k++) {
            total = total + array[i][k];
        }
    }
    return total;
}

上面的代码是计算二维数组中所有数字的总和,但是我正在尝试计算数组中每一行的总数。

    public static int[] rowSums(int[][] array) {
}

我不确定如何为代码计算每行的2D数组。

5 个答案:

答案 0 :(得分:4)

如果您使用的是Java 8,则可以通过以下方式执行此操作:

int[] ar = Arrays.stream(new int[][]{{1,2},{3,5}}) // source
                 .mapToInt(arr -> IntStream.of(arr).sum()) // sum inner array
                 .toArray(); // back to int[]
System.out.println(Arrays.toString(ar)); // print the array

没有流:

int[][] arr = {{1,2},{3,5}};
// create a array that stores the total of each inner array
int[] total = new int[arr.length];
// first loop for outer array
for (int i = 0; i < arr.length; i++) {
    // loop for inner array
    for (int k = 0; k < arr[i].length; k++) {
        // since default value of total[i] is 0, we can directly use +=
        total[i] += arr[i][k];
    }
}
// print the array
System.out.println(Arrays.toString(total));

答案 1 :(得分:4)

你的意思是这样的:

public static int[] sum(int[][] array) {

    //create an array of size array.length
    int[] result = new int[array.length];
    int total;

    //Loop over the first dimension 
    for (int i = 0; i < array.length; i++) {

        total = 0;//Make sure to re-initialize the total in each iteration

        //For each row calculate the sum and store it in total
        for (int k = 0; k < array[i].length; k++) {
            total += array[i][k];
        }

        //When you finish put the result of each row in result[i]
        result[i] = total;
    }
    return result;
}

实施例

System.out.println(
        Arrays.toString(sum(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}}))
);

输出

[3, 4, 6]

答案 2 :(得分:3)

基于@YFC_L回答,但使用增强循环:

public static int[] sum2(int[][] array) {

    //create an array of size based of how many rows the array has
    int[] result = new int[array.length];

    int rowIndex = 0;
    //Loop over each row
    for (int[] row : array) {
        int total = 0;

        //Calculate the sum of the row
        for (int n : row) {
            total += n;
        }

        //Store the sum in the result
        result[rowIndex++] = total;

    }
    return result;
}

此外,这种方法可以用相同的方式进行测试:

public static void main(String[] args) {
    System.out.println(
            Arrays.toString(sum2(new int[][]{{1, 1, 1}, {2, 2}, {3, 3}}))
    );
}

,当然输出是相同的:

[3, 4, 6]

答案 3 :(得分:1)

尝试使用您的代码稍作修改

public static int[] sum(int[][] array) {
    List<Integer> rowTotal = new ArrayList<>();
    int total = 0;
    for (int i = 0; i < array.length; i++) {
        for (int k = 0; k < array[i].length; k++) {
            total = total + array[i][k];
        }
        rowTotal.add(total);
        total = 0;
    }
    return rowTotal.stream().mapToInt(i->i).toArray();
}

答案 4 :(得分:1)

List<Integer> total = sum(ar); 
Integer[] result = total.toArray(new Integer[0]);

如果你需要在获得结果后使用int [],

assertThat(object.getField());

使用结果对象进一步使用。