java - 如何对二维数组进行列和和行和方法?

标签 java arrays methods multidimensional-array

到目前为止,我有一个对列进行总计的方法,但这并不完全是我所需要的。

我需要将每行的总计放在每行的右侧,将每列的总计放在每列的底部。像这样的事情

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;
        }


}

最佳答案

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

打印矩阵后仅再应用一个 for 循环。

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);

关于java - 如何对二维数组进行列和和行和方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891403/

相关文章:

java - 如何正确重新排列 arraylist 以便能够从中提取

c# - 线程安全方法?

Java - 低 "used time"的较短 session 超时

java - Spring boot可复用springdoc-openapi参数注解

java - 如何使用itext在java中的PDF页脚中添加表格

java - Setter 方法有异常

c++ - 隐式对象参数和 this 指针

java - Lucene 每晚构建 javadoc?

c - 如何在 C 中创建字符串(或字符)数组?

javascript - 从 csv 制作二维数组