2014-02-19 74 views
1

到目前爲止,我有一個總計列的方法,但它不完全是我需要的。如何製作二維數組的列和行總和方法?

我需要每行的右側每行的總數,以及每列的底部每列的總數。像這樣的東西

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


} 

回答

2
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); 
+0

那麼只需將這一個添加到方法中?我試過這樣做,但沒有正確顯示。我可能是做錯了 – user3055240

+0

你想矩陣我顯示? – Devavrata

+0

是的。但它並沒有像那樣出來。我將在上面編輯 – user3055240

0

打印陣列後,只是打印的總數在一個單一的行,而不是三行。

+0

我沒跟着。我改變了println來打印,但那不符合我的要求。 – user3055240

+0

「但這不符合我的要求。」 - 它是什麼? – Smutje

+0

好的。我編輯顯示更改打印輸出 – user3055240

-1

您可以使用StringBuilder每個總和追加到一個字符串,然後把它打印出來後,循環結束。

StringBuilder columnTotal = new StringBuilder(); 

for (....){ 
columnTotal.append(sum) 
} 

System.out.println(columnTotal)