首页 > 解决方案 > 如何将多维数组的添加放入同一类中的方法中?

问题描述

public static void main(String [] args) {
    Scanner input = new Scanner(System.in);

    int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;

    int [][] matrix1 = new int[ir1][ic1];

    int [][] matrix2 = new int[ir2][ic2];

    // an example of it is the addition of two matrices put into the method
 
    int total[][] = new int [ir1][ic1]; 

    for (int r = 0; r < matrix1.length; r++) {
       for (int c = 0; c < matrix2[r].length; c++)
          total [r][c] = matrix1[r][c] + matrix2[r][c];
    }
    System.out.println("\nThe addition of two Matrices: ");

    for (int r = 0; r < total.length; r++) {
       for (int c = 0; c < total[r].length; c++)
          System.out.printf("%7d", total[r][c]);
          System.out.println();
    }
  
   // this is where I want to put the addition
   public static int [][] add () {

   }

标签: javamatrixmultidimensional-arraymethods

解决方案


你几乎拥有它。

但请注意:在 Java 中,方法中不能有其他方法。因此,add()方法必须在main()方法之外。

然后你只需要调整参数来接受矩阵并将逻辑移动到方法中:

public static void main(String[] args) {
  /* ... */
  int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
  int[][] matrix1 = new int[ir1][ic1];
  int[][] matrix2 = new int[ir2][ic2];

  int[][] total = add (matrix1, matrix2);
  /* ... */
} 

public static int[][] add (int[][] matrix1, int[][] matrix2) {
  int total[][] = new int [matrix1.length][matrix1[0].length]; 
  for (int r = 0; r < matrix1.length; r++) {
    for (int c = 0; c < matrix2[r].length; c++) {
      total[r][c] = matrix1[r][c] + matrix2[r][c];
    }
  }
  return total;
}

推荐阅读