使用二维数组实现Matrix(矩阵):
1. 定义Matrix(矩阵)类,要求如下:
a) 变量:matrix(int型二维数组),row(行数),column(列数);
b) 方法:实现两个矩阵的乘法,所有方法将返回操作后的结果矩阵。(两个矩阵的乘法:一个m×n的矩阵a(m,n)乘一个n×p的矩阵b(n,p),会得到一个m×p的矩阵c(m,p)。矩阵的行数和列数自定。)
c) 定义构造方法。
2. 编写主类,测试Matrix类。包括:构建对象,测试每一个方法,并将测试结果输出到屏幕上。
输入格式:
按下面格式输入行数、列数和矩阵:
矩阵1:
2 3
1 2 3
4 5 6
矩阵2:
3 2
7 8
9 0
1 2
输出格式:
按下面格式输出乘积矩阵,每行后面有一个空格符和回车换行符:
28 14
79 44
输入样例:
2 3
1 2 3
4 5 6
3 2
7 8
9 0
1 2
结尾无空行
输出样例:
28 14
79 44
结尾无空行
答案代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int[][] arr1 = new int[a][b];
for (int i = 0; i < a; i++){
for (int j = 0; j < b; j++){
arr1[i][j] = sc.nextInt();
}
}
Matrix m1 = new Matrix(a,b,arr1);//构造第一个矩阵
int c = sc.nextInt();
int d = sc.nextInt();
int[][] arr2 = new int[c][d];
for (int i = 0; i < c; i++){
for (int j = 0; j < d; j++){
arr2[i][j] = sc.nextInt();
}
}
Matrix m2 = new Matrix(c,d,arr2);//构造第二个矩阵
Matrix m3 = m1.mul(m2);//两个矩阵相乘,调用的是Matrix里的mul方法,该方法返回类型为矩阵
for (int i = 0; i < m3.ar.length; i++){
for (int j = 0; j < m3.ar[0].length; j++){
System.out.print(m3.ar[i][j]+" ");
}
System.out.println();
}//打印矩阵
}
}
class Matrix {
int h = 0,l = 0;
int[][] ar;
Matrix(){}//无参构造
Matrix(int h,int l,int[][] array){//带参构造
this.h = h;
this.l = l;
ar = array;
}
public Matrix mul(Matrix m2){
Matrix m3 = new Matrix();//注意生成一个新的矩阵对象,便于该方法返回值
m3.ar = new int[this.h][m2.l];
for (int i = 0; i < this.h; i++){
for (int j = 0; j < m2.l; j++){
int sum = 0;
for (int t = 0; t < this.l; t++){
sum = sum + this.ar[i][t] * m2.ar[t][j];//矩阵的乘法,线性代数知识
}
m3.ar[i][j] = sum;
}
}
return m3;
}
}
本题主要考察了类的知识点:
1.类的定义(分为类的成员变量定义以及类的构造方法的定义)
2.方法的调用 形参的数据类型自定义 以及返回类型的自定义