简体   繁体   中英

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. Edit: Got it solved thanks to @KevinAnderson. Needed to append rowSum[r] to Arrays instead of trying to use another for loop to get the values.

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.

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. 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. 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.

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

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:

 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.


See also: Pascal's triangle 2d array - formatting printed output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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