package test;
public class Matrix {
private int rows; // 行
private int cols; // 列
private double[][] data; // 数据
public Matrix() {
}
// 构造方法
public Matrix(int M, int N) {
this.rows = M;
this.cols = N;
data = new double[M][N];
}
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 RuntimeException("Illegal matrix dimensions.");
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.printf("%9.4f ", data[i][j]);
System.out.println();
}
}
@Override
public String toString() {
return "共有" + rows + "行," + cols + "列";
}
public static void main(String[] argv) {
double x[][] = { { 3, 2, 3 }, { 5, 9, 8 }, };
Matrix m = new Matrix(3, 2, x);
double y[][] = { { 4, 7 }, { 9, 3 }};
Matrix m1 = new Matrix(2, 2, y);
System.out.println(m.multiply(m1));
}
}
[color=red]Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test.Matrix.multiply(Matrix.java:43)
at test.Matrix.main(Matrix.java:72)[/color]
帮忙写下测试,和输出打印,谢谢。