publicclassTestMutipleMatrix{publicstaticvoidmain(String[]args){intmatrix1[][]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};intmatrix2[][]={{1,2,3,4},{2,3,4,5},{3,3,3,3}};int[][]res...
public class TestMutipleMatrix {
public static void main(String[] args) {
int matrix1[][] = { { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 }, { 4, 5, 6 } };
int matrix2[][] = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 3, 3, 3 } };
int[][] resultMatrix = resultMatrix(matrix1, matrix2);
System.out.print("行数" + matrix1.length); // 4
System.out.print("列数" + matrix1[0].length); // 3
System.out.println();
printResult(matrix1, matrix2, resultMatrix);
}
public static int[][] resultMatrix(int[][] m1, int[][] m2) {
int[][] resultMuti = new int[m1.length][m1[0].length];
try {
for (int i = 0; i < m1.length; i++)
for (int j = 0; j < resultMuti.length; j++)
for (int k = 0; k < resultMuti[0].length; k++)
resultMuti[i][j] = m1[i][k] * m2[k][j];
} catch (Exception e) {
System.out.print(e);
}
return resultMuti;
}
public static void printResult(int[][] m1, int[][] m2, int[][] m3) {
System.out.print("第1个矩阵:");
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++)
System.out.print(" " + m1[i][j]);
}
System.out.print("\n第2个矩阵:");
for (int i = 0; i < m2.length; i++) {
for (int j = 0; j < m2[0].length; j++)
System.out.print(" " + m2[i][j] + " ");
}
System.out.println("\n矩阵运算之后");
for (int i = 0; i < m3.length; i++) {
for (int j = 0; j < m3[i].length; j++)
System.out.print(" " + m3[i][j]);
}
}
}
这是一个二维数组相乘的问题。Eclipse下运行总有java.lang.ArrayIndexOutOfBoundsException: 3 这个错误!
展开