2014-11-24 64 views
0

我有一行和一列的總和,但我期望單獨找到每行和列的總和。例如,輸出將是「第1行的總和是..排2總和..等等也是一樣的列以及獲取二維數組中每個單獨行和列的總和

public class TwoD { 

    public static void main(String[] args) { 
    int[][] myArray = { {7, 2, 10, 4, 3}, 
         {14, 3, 5, 9, 16}, 
         {99, 12, 37, 4, 2}, 
         {8, 9, 10, 11, 12}, 
         {13, 14, 15, 16, 17}     
    }; 

    int row = 0; 
    int col; 
    int rowSum = 0; 
    int colSum = 0; 

    for(col = 0; col<5;col++) 
     rowSum = rowSum + myArray[row][col]; 
     for(row = 0; row<5; row++) 
     System.out.println("Sum of row " + row + " is " + rowSum); 

    col = 0; 
    for(row=0; row<5;row++) 
    colSum = colSum + myArray[row][col]; 
     for(col = 0; col<5; col++) 
     System.out.println("Sum of column " + col + " is " + colSum);  
    } 
} 
+0

這輸出每行和列,但我得到相同的總和爲每個行/列輸出 – user3247712 2014-11-24 09:26:26

回答

0

爲了使它更整潔,可以通過一種方法存儲在一維陣列中的每個行的總和。

public static void main(String[] args) 
{ 
    int[][] table = {......}; //where ... is your array data 
    int[] sumOfRows = sumTableRows(table); 
    for (int x = 0; x < table.length; x++) 
    { 
     for (int y = 0; y < table[x].length; y++) 
      System.out.print(table[x][y] + "\t"); 
     System.out.println("total: " + sumTableRows[x]); 
    } 
} 

public static int[] sumTableRows(int[][] table) 
{ 
    int rows = table.length; 
    int cols = table[0].length; 

    int[] sum = new int[rows]; 
    for(int x=0; x<rows; x++) 
     for(int y=0; y<cols; y++) 
      sum[x] += table[x][y]; 
    return sum;  
} 
0

你錯過了一條線,這樣使用:。

for(col = 0; col<5;col++) { 
    for(row = 0; row<5; row++) { 
     rowSum = rowSum + myArray[row][col]; 
    } 
    System.out.println("Sum of row " + rowSum); 
    rowSum=0; // missed this line... 
} 

同樣,

for(row=0; row<5;row++) { 
    for(col = 0; col<5; col++) { 
     colSum = colSum + myArray[row][col]; 
    } 
    System.out.println("Sum of column " + colSum); 
    colSum=0; 
}