编写一个主类,包括3个方法。在main方法中,定义两个整数矩阵,分别调用矩阵加matrixadd()和矩阵乘matrixmultiply()两个方法,输出运算结果。
时间: 2023-04-16 08:03:27 浏览: 306
好的,以下是主类的代码:
```
public class MatrixCalculator {
// 矩阵加法
public static int[][] matrixAdd(int[][] matrix1, int[][] matrix2) {
int row = matrix1.length;
int col = matrix1[].length;
int[][] result = new int[row][col];
for (int i = ; i < row; i++) {
for (int j = ; j < col; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}
// 矩阵乘法
public static int[][] matrixMultiply(int[][] matrix1, int[][] matrix2) {
int row1 = matrix1.length;
int col1 = matrix1[].length;
int col2 = matrix2[].length;
int[][] result = new int[row1][col2];
for (int i = ; i < row1; i++) {
for (int j = ; j < col2; j++) {
for (int k = ; k < col1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
// 输出矩阵
public static void printMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[].length;
for (int i = ; i < row; i++) {
for (int j = ; j < col; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{5, 6}, {7, 8}};
int[][] result1 = matrixAdd(matrix1, matrix2);
int[][] result2 = matrixMultiply(matrix1, matrix2);
System.out.println("矩阵加法结果:");
printMatrix(result1);
System.out.println("矩阵乘法结果:");
printMatrix(result2);
}
}
```
在main方法中,我们定义了两个2x2的整数矩阵matrix1和matrix2,然后分别调用了矩阵加法和矩阵乘法方法,并输出了运算结果。其中,printMatrix方法用于输出矩阵。
阅读全文