2016-05-12 22 views
2

請幫助,我應該使用兩個單獨的方法(一個用於列,一個用於行),以總結每個單獨的行和列的二維數組並打印出來(例如:行1 =,行2 =,列1 =,列2 =)。到目前爲止,我有兩個單獨的方法,它們分別只讓我第一行和第一列,但我堅持如何在不更改返回值的情況下打印出其他行/列。這是我到目前爲止有:使用兩種方法添加行和列

public class FinalSumRowColumn 
{ 
    public static void main(String[] args) 
    { 

     int[][] mat = { 
         { 1, 2, 3 }, 
         { 4, 5, 6 }, 
         { 7, 8, 9 } 
         }; 

     System.out.println("\nSum Row 1 = " + sumRow(mat)); 
     System.out.println("\nSum Col 1 = " + sumCol(mat)); 
    } 

    public static int sumRow(int[][] mat) 
    { 
     int total = 0; 

      for (int column = 0; column < mat[0].length; column++) 
      { 
       total += mat[0][column]; 
      } 
     return total; 
    } 

    public static int sumCol(int[][] mat) 
    { 
     int total = 0; 

      for (int row = 0; row < mat[0].length; row++) 
      { 
       total += mat[row][0]; 
      } 
     return total; 
    } 
} 
+0

爲什麼你返回一個'int'而不是一個數組總和? – RealSkeptic

+0

方法應該返回一個*特定*列/行的總和,或者它們的總和? –

回答

1

添加rowcol參數對於這些方法,例如:

public class FinalSumRowColumn { 
    public static void main(String[] args) { 

     int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 

     System.out.println("\nSum Row 1 = " + sumRow(mat, 0)); 
     System.out.println("\nSum Col 1 = " + sumCol(mat, 0)); 
     System.out.println("\nSum Row 1 = " + sumRow(mat, 1)); 
     System.out.println("\nSum Col 1 = " + sumCol(mat, 1)); 
     System.out.println("\nSum Row 1 = " + sumRow(mat, 2)); 
     System.out.println("\nSum Col 1 = " + sumCol(mat, 2)); 
    } 

    public static int sumRow(int[][] mat, int row) { 
     int total = 0; 

     for (int column = 0; column < mat[row].length; column++) { 
      total += mat[row][column]; 
     } 
     return total; 
    } 

    public static int sumCol(int[][] mat, int col) { 
     int total = 0; 

     for (int row = 0; row < mat[0].length; row++) { 
      total += mat[row][col]; 
     } 
     return total; 
    } 
} 
+0

不錯,我只需要改變行/列號,否則完美。 Muchas Gracias Amigo。 – user3117238

1

你爲什麼不參數同時添加到您的方法來指示要進行求和的行或列的索引?

例如public static int sumRow(int[][] mat, int row)

+0

啊哈!我忽略了添加參數的主要細節。謝謝,我會嘗試。 – user3117238

1

你的方法定義更改來自:

public static int sumRow(int[][] mat) 

到:

public static int sumRow(int[][] mat, int row) 

再後來就和該行傳遞給方法:

total += mat[row][column]; 

同樣適用於sumCol()

0

一個參數添加到每個方法:int index,例如:

public static int sumRow(int[][] mat, int index) 
{ 
    int total = 0; 

    for (int column = 0; column < mat[index].length; column++) 
    { 
     total += mat[index][column]; 
    } 
    return total; 
} 

當你打印:

for (int i = 0; i < mat.length; i++) { 
    System.out.println("Sum Row " + (i+1) + " = " + sumRow(mat, i)); 
}