两个二维数组求和

Two 2d Arrays Sum

我正在尝试获取两个二维数组输入,然后将它们相加,但无法正确编译。出于某种原因,如果我在代码编译的方法之外声明 'addedMatrix' 但 addedMatrix 为空

这是我目前的情况:

System.out.print("Enter Matrix 1 : ");
double[][] matrix1 = new double[3][3];

for (int r = 0; r < matrix1.length; r++)
{
    for (int c = 0; c < matrix1[0].length; c++)
    {
        matrix1[r][c] = input.nextDouble();
    }
}

System.out.print("Enter Matrix 2 : ");
double[][] matrix2 = new double[3][3];

for (int r = 0; r < matrix2.length; r++)
{
    for (int c = 0; c < matrix2[0].length; c++)
    {
        matrix2[r][c] = input.nextDouble();
    }
}

addMatrix(matrix1, matrix2);

System.out.println("The matrices added are : ");

for (int r = 0; r < addedMatrix.length; r++)
{
    for (int c = 0; c < addedMatrix[0].length; c++)
    {
        System.out.print(addedMatrix[r][c]+ " ");
    }

    System.out.println();
}

public static double[][] addMatrix(double[][] arr1, double[][] arr2)
{
    double[][] addedMatrix = new double[3][3];
        
    for (int r = 0; r < addedMatrix.length; r++)
    {
        for (int c = 0; c < addedMatrix[0].length; c++)
        {
            addedMatrix[r][c] = arr1[r][c] + arr2[r][c];
        }
    }
        
    return addedMatrix;
}

你的语法完全错误首先你需要一个main函数然后你还需要接受return类型。

import java.util.Scanner;

public class Test {


public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter Matrix 1 : ");
    double[][] matrix1 = new double[3][3];
    for(int r = 0; r < matrix1.length; r++)
    {
        for(int c = 0; c < matrix1[0].length; c++)
        {
            matrix1[r][c] = input.nextDouble();
        }
    }
    System.out.print("Enter Matrix 2 : ");
    double[][] matrix2 = new double[3][3];
    for(int r = 0; r < matrix2.length; r++)
    {
        for(int c = 0; c < matrix2[0].length; c++)
        {
            matrix2[r][c] = input.nextDouble();
        }
    }

    double[][] addedMatrix = addMatrix(matrix1, matrix2);

    System.out.println("The matrices added are : ");
    for(int r = 0; r < addedMatrix.length; r++)
    {
        for(int c = 0; c < addedMatrix[0].length; c++)
        {
            System.out.print(addedMatrix[r][c]+ " ");
        }
        System.out.println();
    }
}

public static double[][] addMatrix(double[][] arr1, double[][] arr2)
{
    double[][] addedMatrix = new double[3][3];
    for(int r = 0; r < addedMatrix.length; r++)
    {
        for(int c = 0; c < addedMatrix[0].length; c++)
        {
            addedMatrix[r][c] = arr1[r][c] + arr2[r][c];
        }
    }
    return addedMatrix;
}
}