java读取txt矩阵文件_从文本文件中读入矩阵数据源JAVA版并且提供矩阵的加减运算,如果两个矩阵不符合矩阵运算规则,请抛出异常对象
时间: 2023-06-21 19:20:45 浏览: 97
java读取txt文档的
好的,以下是Java语言的代码示例,实现从文本文件中读入矩阵数据源并提供矩阵的加减运算,如果两个矩阵不符合矩阵运算规则,则抛出异常对象:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Matrix {
private int[][] data;
private int rows;
private int cols;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.data = new int[rows][cols];
}
public void set(int row, int col, int value) {
this.data[row][col] = value;
}
public int get(int row, int col) {
return this.data[row][col];
}
public Matrix add(Matrix other) throws RuntimeException {
if (this.rows != other.rows || this.cols != other.cols) {
throw new RuntimeException("Matrix dimensions must agree.");
}
Matrix result = new Matrix(this.rows, this.cols);
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
result.set(i, j, this.get(i, j) + other.get(i, j));
}
}
return result;
}
public Matrix subtract(Matrix other) throws RuntimeException {
if (this.rows != other.rows || this.cols != other.cols) {
throw new RuntimeException("Matrix dimensions must agree.");
}
Matrix result = new Matrix(this.rows, this.cols);
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
result.set(i, j, this.get(i, j) - other.get(i, j));
}
}
return result;
}
public static Matrix readFromFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
int rows = 0;
int cols = 0;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
rows++;
if (cols == 0) {
cols = values.length;
} else if (cols != values.length) {
throw new RuntimeException("Invalid matrix data.");
}
}
br.close();
Matrix result = new Matrix(rows, cols);
br = new BufferedReader(new FileReader(fileName));
int row = 0;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
for (int col = 0; col < values.length; col++) {
result.set(row, col, Integer.parseInt(values[col]));
}
row++;
}
br.close();
return result;
}
public static void main(String[] args) {
try {
Matrix a = Matrix.readFromFile("matrix1.txt");
Matrix b = Matrix.readFromFile("matrix2.txt");
System.out.println("Matrix A:");
a.print();
System.out.println("Matrix B:");
b.print();
System.out.println("Matrix A + B:");
a.add(b).print();
System.out.println("Matrix A - B:");
a.subtract(b).print();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void print() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
System.out.print(this.get(i, j) + " ");
}
System.out.println();
}
}
}
```
在上面的示例代码中,我们首先定义了一个`Matrix`类,其中包含了一些矩阵的基本操作,如矩阵的赋值、获取、加减运算等。接下来,我们实现了一个静态方法`readFromFile()`,用于从文本文件中读取矩阵数据。在读取数据时,我们首先遍历整个文本文件,以确定矩阵的行数和列数,并检查每一行数据的列数是否一致。如果数据不符合矩阵规则,则抛出异常对象。然后,我们再次遍历文本文件,将数据存储到一个矩阵对象中。
最后,我们在`main()`方法中读取两个矩阵`A`和`B`,并对它们进行加减运算,然后打印出结果。如果矩阵的维度不匹配,将会抛出异常对象并打印异常信息。
阅读全文