有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将多维数组的附加项放入同一类中的方法中?

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 () {

   }

共 (1) 个答案

  1. # 1 楼答案

    你差点就成功了

    但请注意:在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;
    }