简体   繁体   English

在每行之后打印二维数组中行的总和

[英]Print the sum of the row in a 2D Array after each row

I'm trying to get the sum of each row printed out after that row.我试图在该行之后打印出每一行的总和。 It needs to be formatted like this它需要像这样格式化

2 5 6 3| 16
9 4 4 7| 24
1 10 2 3| 16
8 4 5 3| 20
-----------------
20 23 17 16| 76

Doesn't have to be as nice, but close to it.不一定要好,但要接近。 I have to use a toString method, here is what I have so far.我必须使用 toString 方法,这是我到目前为止所拥有的。 Edit: Got it solved thanks to @KevinAnderson.编辑:感谢@KevinAnderson 解决了。 Needed to append rowSum[r] to Arrays instead of trying to use another for loop to get the values.需要 append rowSum[r]到 Arrays 而不是尝试使用另一个 for 循环来获取值。

public String toString() {
    //Stores the colSum into a string col
    String col = "";
    for (int j = 0; j < cell[0].length; j++) {
        col += " " + colSum[j];

    }
    //Calculates the total of both the rows and columns
    for (int i = 0; i < cell.length; i++) {
        for (int j = 0; j < cell[0].length; j++) {
            grandTotal += cell[i][j];
        }
    }
    //Prints the array
    String array = "";
    for (int r = 0; r < cell.length; r++) {
        for (int c = 0; c < cell[r].length; c++) {
            array += " " + cell[r][c];
        }
        array += "|" + +rowSum[r] + "\n";
    }
    return array + "-----------------" + "\n" + col + "| " + grandTotal;
}

rowSum and colSum are calculated in a separate method that can be provided if need be, but they do work as intended. rowSumcolSum在单独的方法中计算,如果需要,可以提供,但它们确实按预期工作。

What I believe I need to do is store the value of rowSum in either an int value and print it, or increment through rowSum in some way.我相信我需要做的是将rowSum的值存储在一个 int 值中并打印它,或者以某种方式通过rowSum递增。 I've tried both, and so far it prints out the whole array that it is stored into.我都试过了,到目前为止它会打印出它存储的整个数组。

Here a solution by using two for-loops.这是使用两个 for 循环的解决方案。 One to print the sum of the rows the other to print the sum of the columns Also to build the whole sum get track of it either in the first or the second for-loop.一个打印行的总和另一个打印列的总和还要构建整个总和在第一个或第二个 for 循环中对其进行跟踪。

package so;

import java.util.*;

public class RemoveString {
    public static void main(String[] args) {
        int[][] arr = {{2, 5, 6, 3}, {9, 4, 4, 7}, {1, 10, 2, 3}, {8, 4, 5, 3}};
        System.out.println(toString(arr));
    }

    public static String toString(int[][] cell) {
        int sum = 0;
        int allSum = 0;
        int counter = 0;
        String resultString = "";

        for (int i = 0; i < cell.length; i++) {
            for (int j = 0; j < cell[i].length; j++) {
                // Count the columns for the condition later on
                if (i == 0) {
                    counter++;
                }
                sum += cell[i][j];
                resultString += cell[i][j] + " ";
            }
            resultString += "| " + sum + "\n";
            sum = 0;
        }

        resultString += "--------------\n";

        for (int i = 0; i < counter; i++) {
            for (int j = 0; j < cell.length; j++) {
                sum += cell[j][i];
            }
            allSum += sum;
            resultString += sum + " ";
            sum = 0;
        }

        resultString += "|" + allSum;
        return resultString;
    }
}

Creates the output创建 output

2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
--------------
20 23 17 16 |76

You can first prepare two arrays of sums by rows and columns , then it is easier to print this:您可以先准备两个 arrays 按求和,然后更容易打印:

 2  5  6  3 | 16
 9  4  4  7 | 24
 1 10  2  3 | 16
 8  4  5  3 | 20
----------------
20 23 17 16 | 76

Code:代码:

// assume that we have a rectangular array
int[][] arr = {
        {2, 5, 6, 3},
        {9, 4, 4, 7},
        {1, 10, 2, 3},
        {8, 4, 5, 3}};

// array of sums by rows
int[] sum1 = Arrays.stream(arr)
        .mapToInt(row -> Arrays.stream(row).sum())
        .toArray();

// array of sums by columns
int[] sum2 = Arrays.stream(arr)
        .reduce((row1, row2) -> IntStream
                .range(0, row1.length)
                .map(i -> row1[i] + row2[i])
                .toArray())
        .orElse(null);
// output
IntStream.range(0, arr.length)
        // iterate over the indices of the rows of an array
        .peek(i -> Arrays.stream(arr[i])
                // elements of the row
                .forEach(e -> System.out.printf("%2d ", e)))
        // sum of the row
        .peek(i -> System.out.printf("| %2d", sum1[i]))
        // end of the row, new line
        .forEach(i -> System.out.println());

// line of hyphens, assume that all numbers are two-digit
System.out.println("-" .repeat(arr[0].length * 2 + arr[0].length + 4));

// line of sums by columns
IntStream.range(0, sum2.length)
        // sum of column
        .forEach(i -> System.out.printf("%2d ", sum2[i]));

// last number, sum of sums, total
System.out.printf("| %2d", Arrays.stream(sum2).sum());

"%2d" - format as a two-digit number. "%2d" - 格式为两位数


See also: Pascal's triangle 2d array - formatting printed output另请参阅: Pascal 的三角形二维数组 - 格式化打印 output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM