2016-05-12 8 views
2

2次元配列の各行と列を合計してそれらを出力するには、2つの別々のメソッド(1つは列、1つは行)例:行1 =、行2 =、列1 =、列2 =)。これまでは、最初の行とカラムを別々に取得する2つのメソッドがありますが、戻り値を変更せずに他の行/列を出力する方法については固執しています。ここで私がこれまで持っているものです。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

ニース、私はちょうど行/列番号を変更する必要があった、そうでなければ完璧。ムチャス・グラシアス・アミーゴ。 – user3117238

1

なぜあなたは合計する行または列のインデックスを示すために、両方のあなたの方法にパラメータを追加しませんか?例えば

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

+0

Aha!私は、パラメータを追加するための主要な細部を見落としました。私はそれを試していただきありがとうございます。 – user3117238

1
はからあなたのメソッドの定義を変更し

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

へ:

:メソッドに渡された後、

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

以降合計の行

total += mat[row][column]; 

同じことがsumCol()になります。

0

は、各メソッドに1つの以上のパラメータを追加します。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)); 
} 
関連する問題