/*filename:P6Q23.java
*Name:Wang Chaoran
*Description:
23 (Adding two matrices)
Write a method to add two matrices. The header of the method is as follows:
public static int[][] addMatrix(int[][] a, int[][] b)
In order to be added, the two matrices must have the same dimensions and the same or compatible
types of elements. As shown below, two matrices are added by adding the two elements of the arrays with the same index:
*/
import java.util.Scanner;
class P6Q23{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please input the dimention value for a (m x n) matris.\nPlease input m:");
int m=scan.nextInt();
System.out.println("Please input n:");
int n=scan.nextInt();
int[][] a = new int[n][m];
int[][] b = new int[n][m];
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
a[i][j]=(int)(Math.random()*10);
b[i][j]=(int)(Math.random()*10);
}
}
System.out.println("Matrix a:");
print(a);
System.out.println("Matrix b:");
print(b);
System.out.println("Add Matrix a,b: ");
print(addMatrix(a,b));
}
public static void print(int[][] matrix){
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[i].length;j++)
System.out.printf("%-5d",matrix[i][j]);
System.out.println();
}
System.out.println();
}
public static int[][] addMatrix(int[][] a,int[][] b){
int[][] combine= new int[a.length][a[0].length];
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
combine[i][j]=a[i][j]+b[i][j];
return combine;
}
}