用java编写一个矩阵类,其中封装有一个代表矩阵的二维数组,并提供一个实现两个不同行列矩阵的相加方法。利用随机函数产生两个3行4列的矩阵,验证类实验。
时间: 2023-05-26 19:06:54 浏览: 186
代码如下:
```java
import java.util.Random;
public class Matrix {
private int[][] matrix;
private int row;
private int col;
public Matrix(int[][] matrix) {
this.matrix = matrix;
this.row = matrix.length;
this.col = matrix[0].length;
}
public Matrix add(Matrix other) {
if (this.row != other.row || this.col != other.col) {
throw new IllegalArgumentException("Matrices do not have the same size");
}
int[][] result = new int[this.row][this.col];
for (int i = 0; i < this.row; i++) {
for (int j = 0; j < this.col; j++) {
result[i][j] = this.matrix[i][j] + other.matrix[i][j];
}
}
return new Matrix(result);
}
public static void main(String[] args) {
Random r = new Random();
int[][] matrix1 = new int[3][4];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
matrix1[i][j] = r.nextInt(10);
}
}
int[][] matrix2 = new int[3][4];
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
matrix2[i][j] = r.nextInt(10);
}
}
Matrix m1 = new Matrix(matrix1);
Matrix m2 = new Matrix(matrix2);
Matrix result = m1.add(m2);
System.out.println("Matrix 1: ");
printMatrix(m1);
System.out.println("Matrix 2: ");
printMatrix(m2);
System.out.println("Result: ");
printMatrix(result);
}
private static void printMatrix(Matrix matrix) {
for (int i = 0; i < matrix.row; i++) {
for (int j = 0; j < matrix.col; j++) {
System.out.print(matrix.matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
运行结果如下:
```
Matrix 1:
0 7 7 3
3 8 7 2
2 3 7 2
Matrix 2:
7 5 5 7
7 9 9 8
7 1 1 7
Result:
7 12 12 10
10 17 16 10
9 4 8 9
```
阅读全文