用Java 编写程序实现对矩阵的加法、减法和乘法运算。
时间: 2023-05-20 11:01:12 浏览: 74
好的,以下是 Java 编写程序实现对矩阵的加法、减法和乘法运算的示例代码:
```java
public class Matrix {
private int[][] data;
private int rows;
private int cols;
public Matrix(int[][] data) {
this.data = data;
this.rows = data.length;
this.cols = data[0].length;
}
public Matrix add(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = this.data[i][j] + other.data[i][j];
}
}
return new Matrix(result);
}
public Matrix subtract(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrices must have the same dimensions");
}
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = this.data[i][j] - other.data[i][j];
}
}
return new Matrix(result);
}
public Matrix multiply(Matrix other) {
if (this.cols != other.rows) {
throw new IllegalArgumentException("The number of columns in the first matrix must be equal to the number of rows in the second matrix");
}
int[][] result = new int[this.rows][other.cols];
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < other.cols; j++) {
for (int k = 0; k < this.cols; k++) {
result[i][j] += this.data[i][k] * other.data[k][j];
}
}
}
return new Matrix(result);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(data[i][j]).append(" ");
}
sb.append("\n");
}
return sb.toString();
}
}
```
使用示例:
```java
int[][] data1 = {{1, 2}, {3, 4}};
int[][] data2 = {{5, 6}, {7, 8}};
Matrix matrix1 = new Matrix(data1);
Matrix matrix2 = new Matrix(data2);
// 加法
Matrix sum = matrix1.add(matrix2);
System.out.println("Sum:\n" + sum);
// 减法
Matrix difference = matrix1.subtract(matrix2);
System.out.println("Difference:\n" + difference);
// 乘法
Matrix product = matrix1.multiply(matrix2);
System.out.println("Product:\n" + product);
```
输出结果:
```
Sum:
6 8
10 12
Difference:
-4 -4
-4 -4
Product:
19 22
43 50
```