Summing Two Matrices in Java

Problem:

Write a program that calculates sum two matrices.


Output:

Enter matrix1: 1 2 3 4 5 6 7 8 9
Enter matrix2: 1 2 3 4 5 6 7 8 9
1.0 2.0 3.0     1.0 2.0 3.0   2.0  4.0  6.0
4.0 5.0 6.0  +  4.0 5.0 6.0 = 8.0  10.0 12.0
7.0 8.0 9.0     7.0 8.0 9.0   14.0 16.0 18.0


Solution:

 import java.util.Scanner;

public class AddingMatricies
{
  public static double[][] addMatrix(double[][] a, double[][] b)
  {
    double[][] c = new double[3][3];
    for (int i =0;i<c.length;i++)
    {
      for (int j =0;j< c[i].length;j++)
      {
        c[i][j]=a[i][j] + b[i][j];
      }
    }
    
    return c;
  }
  public static double[][] readA()
  {
    System.out.print("Enter matrix1: ");
    Scanner scan = new Scanner (System.in);
    double[][] a = new double[3][3];
    for (int i =0;i<a.length;i++)
    {
      for (int j =0;j< a[i].length;j++)
      {
        a[i][j] = scan.nextInt();
      }
    }
    return a;
    
  }
  
  public static double[][] readB()
  {
    System.out.print("Enter matrix2: ");
    Scanner scan = new Scanner (System.in);
    double[][] b = new double[3][3];
    for (int i =0;i<b.length;i++)
    {
      for (int j =0;j< b[i].length;j++)
      {
        b[i][j] = scan.nextInt();
      }
    }
    return b;
    
  }
  
  public static void printSolution(double[][] a, double[][] b, double[][] c)
  {
    for (int i =0; i< a.length;i++)
    {
      for (int j =0;j< a[i].length;j++)
      {
        System.out.print(a[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  +  ");
      else 
      System.out.print("     ");
      for (int j =0;j< b[i].length;j++)
      {
        System.out.print(b[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  =  ");
      else 
      System.out.print("     ");
      for (int j =0;j< c[i].length;j++)
      {
        System.out.print(c[i][j] + " ");
      }
      
      System.out.println();
    }
  }
  public static void main (String[] args)
  {
    double[][] a = readA();
    double[][] b = readB();
    double[][] c = addMatrix(a,b);
    printSolution(a,b,c);
  }
}

1 comment: