要求:程序运行后要求用户分别输入两个矩阵的行数和列数,然后判断两个矩阵是否可以相乘,如果可以相乘,则计算矩阵相乘后的结果,并按矩阵的格式输出;若不能相乘,则提示用户矩阵不相容,并退出程序。
提示:一个2行3列的矩阵可以用一个二维数组表示:int matrixA[2][3]。此外,必须要知道什么是矩阵相乘。矩阵相乘的概念如下图所示:
代码块如下:
/**
*
* @author 芳芳
*
*/
import java.util.Scanner;
public class matrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//定义三个行列不超过20的矩阵
int[][] matrix1 = new int[20][20];
int[][] matrix2 = new int[20][20];
int[][] matrix3 = new int[20][20];
System.out.println("Please input the lines and rows of the two matrices in order");
System.out.println("the line of matrix1:");
int m1 = scanner.nextInt();
System.out.println("the row of matrix1:");
int n1 = scanner.nextInt();
System.out.println("the line of matrix2:");
int m2 = scanner.nextInt();
System.out.println("the row of matrix2:");
int n2 = scanner.nextInt();
if(m1 == n2) {
//判断两个矩阵是否可以相乘
System.out.println("please input the numbers of matrix1");
//读入matrix1的数
for(int i = 0;i < m1;i++) {
for(int j = 0;j < n1;j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("please input the numbers of matrix2");
//读入matrix2的数
for(int i = 0;i < m1;i++) {
for(int j = 0;j < n1;j++) {
matrix2[i][j] = scanner.nextInt();
}
}
//作两个矩阵的乘法
for(int i = 0;i < m1;i++) {
for(int j = 0;j < n2;j++) {
matrix3[i][j] = matrix1[i][j]*matrix2[j][i];
}
}
//输出结果
System.out.println("The result of multiplication of these two matrices is");
for(int i = 0;i < m1;i++) {
for(int j = 0;j < n2;j++) {
System.out.print(matrix3[i][j]+" ");
}
System.out.println();
}
}else {
//不能相乘则提示
System.out.println("These two matrices cannot be multiplied!!!");
}
}
}
当两个矩阵能相乘时运行结果如下:
当两个矩阵不能相乘时运行结果如下: