设计矩阵类Matrix,实现矩阵的加减法运算以及equals()方法和toString()方法。以及提供输入输出
时间: 2023-05-28 15:06:14 浏览: 162
Matrix类的代码:
```java
public class Matrix {
private int rows;
private int cols;
private int[][] data;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
data = new int[rows][cols];
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public int getData(int row, int col) {
return data[row][col];
}
public void setData(int row, int col, int value) {
data[row][col] = value;
}
public Matrix add(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("两个矩阵的行列数不相等!");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.setData(i, j, this.data[i][j] + other.data[i][j]);
}
}
return result;
}
public Matrix subtract(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("两个矩阵的行列数不相等!");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.setData(i, j, this.data[i][j] - other.data[i][j]);
}
}
return result;
}
public boolean equals(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
return false;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (this.data[i][j] != other.data[i][j]) {
return false;
}
}
}
return true;
}
@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();
}
public static Matrix fromInput() {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的行数:");
int rows = scanner.nextInt();
System.out.print("请输入矩阵的列数:");
int cols = scanner.nextInt();
Matrix matrix = new Matrix(rows, cols);
System.out.println("请按行输入矩阵数据,每个数据之间用空格隔开:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix.setData(i, j, scanner.nextInt());
}
}
return matrix;
}
public void print() {
System.out.println(this);
}
}
```
使用示例:
```java
public class MatrixTest {
public static void main(String[] args) {
Matrix a = Matrix.fromInput();
Matrix b = Matrix.fromInput();
System.out.println("矩阵 a:");
a.print();
System.out.println("矩阵 b:");
b.print();
Matrix c = a.add(b);
System.out.println("矩阵 a + b:");
c.print();
Matrix d = a.subtract(b);
System.out.println("矩阵 a - b:");
d.print();
System.out.println("a 是否等于 b:" + a.equals(b));
}
}
```
使用说明:
1. 通过`Matrix.fromInput()`方法从控制台输入矩阵数据;
2. 通过`Matrix.print()`方法输出矩阵;
3. 通过`Matrix.add()`方法计算矩阵的加法;
4. 通过`Matrix.subtract()`方法计算矩阵的减法;
5. 通过`Matrix.equals()`方法判断两个矩阵是否相等。
阅读全文