【问题标题】:Print the sum of the row in a 2D Array after each row在每行之后打印二维数组中行的总和
【发布时间】:2021-02-20 14:15:12
【问题描述】:

我试图在该行之后打印出每一行的总和。需要这样格式化

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

不必那么好,但接近它。我必须使用 toString 方法,这是我到目前为止所拥有的。 编辑:感谢@KevinAnderson 解决了。需要将 rowSum[r] 附加到数组,而不是尝试使用另一个 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 和 colSum 以单独的方法计算,如果需要,可以提供,但它们确实按预期工作。

我认为我需要做的是将 rowSum 的值存储在 int 值中并打印出来,或者以某种方式递增 rowSum。我都试过了,到目前为止它会打印出它存储到的整个数组。

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    这里是使用两个 for 循环的解决方案。 一个打印行的总和另一个打印列的总和 还要在第一个或第二个 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;
        }
    }
    

    创建输出

    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
    

    【讨论】:

      【解决方案2】:

      你可以先用rows和columns准备两个sums数组,这样打印起来比较容易:

       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
      

      代码:

      // 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" - 格式为 两位 数字。


      另见:Pascal's triangle 2d array - formatting printed output

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多