public class Matrix {
private int rows; // 行
private int cols; // 列
private double[][] data; // 数据
public Matrix() {
this(0,0);
}
// 构造方法
public Matrix(int rows, int cols) {
this(rows,cols,new double[rows][cols]);
}
public Matrix(int rows, int cols, double data[][]) {
this.rows = rows;
this.cols = cols;
this.data = data;
}
public double getData(int row, int col) {
return data[row][col];
}
public void setData(int row, int col, double value) {
data[row][col] = value;
}
// 两个矩阵相乘
public Matrix multiply(Matrix B) {
Matrix A = this;
if (A.cols != B.rows)
throw new IllegalArgumentException("矩阵不匹配!");
Matrix C = new Matrix(A.rows, B.cols);
for (int i = 0; i < C.rows; i++)
for (int j = 0; j < C.cols; j++)
for (int k = 0; k < A.cols; k++)
C.data[i][j] += (A.data[i][k] * B.data[k][j]);
return C;
}
// 打印矩阵到控制台
public void show() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
System.out.print(" "+data[i][j]);
System.out.println();
}
}
public String toString() {
// return "相乘后的矩阵共有 " + rows + " 行," + cols + "列 ";
StringBuffer s = new StringBuffer();
int rows = data.length;
int cols = data[0].length;
s.append("Matrix[" + rows + "][" + cols + "] = " + "\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
s.append(" " + data[i][j] + " ");
s.append("\n");
}
s.append("\n");
return s.toString();
}
}
编写MatrixTest类。在该类中通过键盘输入方式确定所要创建的两个矩阵的行列数,根据行列数随机生成数据或键盘输入,并通过setData方法生成矩阵的内容。