有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何为二维数组生成列和行和方法?

到目前为止,我已经有了一个对列进行合计的方法,但这并不是我所需要的

我需要在每行的右边有每行的总数,在每列的底部有每列的总数。像这样的

1  2  3  4  =  10
3  4  5  6  =  18

4  6  8  10  < - Total

我现在得到的是每列的总数,但不是列下的总数

方法

    // method to add the sum of columns
    public static int[] columnSum(int x[][]){
          int temp[] = new int[x[0].length];

            for (int i = 0; i < x[0].length; i++){
                int sum = 0;

                for (int j = 0; j < x.length; j++){
                    sum += x[j][i];

                }
                temp[i] = sum;
                System.out.println("Index is: " + i + " Sum is: "+sum);

            }

            return temp;
        }


}

共 (3) 个答案

  1. # 1 楼答案

    This is the array
    1   2   3   
    2   3   4 
    3   5   7
    

    打印矩阵后,仅为循环应用一个

    System.out.println("This is the sum of the columns");
    int temp[]=columnSum(firstarray);
    for(int i=0;i<columns;i++)
    {
        System.out.print(temp[i]+"\t");
     }
     System.out.println();
    

    取代

    System.out.println("This is the sum of the columns");
    columnSum(firstarray);
    
  2. # 2 楼答案

    您可以使用stringbuilder将每个总和附加到字符串中,然后在循环结束后将其打印出来

    StringBuilder columnTotal = new StringBuilder();
    
    for (....){
     columnTotal.append(sum)
    }
    
    System.out.println(columnTotal)
    
  3. # 3 楼答案

    打印数组后,只需在一行而不是三行中打印总数