Skip to content
Advertisement

Two 2d Arrays Sum

I’m trying to take two 2d array inputs, and then add them together, but it won’t compile correctly. For some reason if i declare the ‘addedMatrix’ outside of the method the code compiles but the addedMatrix is blank

Heres what I have so far :

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;
}

Advertisement

Answer

Your syntax is wrong completely firstly you need a main function and then you also need to accept the return type.

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;
}
}
Advertisement