在Java中,可以使用不同的方式读取矩阵数组。下面是几种常见的方法:
import java.util.Scanner;
public class MatrixReader {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的行数:");
int rows = scanner.nextInt();
System.out.print("请输入矩阵的列数:");
int cols = scanner.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("请输入矩阵的元素:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.println("输入的矩阵为:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MatrixReader {
public static void main(String[] args) {
String filePath = "matrix.txt"; // 文件路径
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int rows = 0;
int cols = 0;
// 获取矩阵的行数和列数
while ((line = reader.readLine()) != null) {
rows++;
cols = line.split(" ").length;
}
int[][] matrix = new int[rows][cols];
// 重新读取文件,填充矩阵
reader.close();
reader = new BufferedReader(new FileReader(filePath));
int row = 0;
while ((line = reader.readLine()) != null) {
String[] elements = line.split(" ");
for (int col = 0; col < cols; col++) {
matrix[row][col] = Integer.parseInt(elements[col]);
}
row++;
}
System.out.println("读取的矩阵为:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
public class MatrixReader {
public static void main(String[] args) {
double[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
RealMatrix matrix = MatrixUtils.createRealMatrix(array);
System.out.println("读取的矩阵为:");
for (int i = 0; i < matrix.getRowDimension(); i++) {
for (int j = 0; j < matrix.getColumnDimension(); j++) {
System.out.print(matrix.getEntry(i, j) + " ");
}
System.out.println();
}
}
}
以上是在Java中以不同方式读取矩阵数组的几种方法。根据具体的需求和场景,选择合适的方法来读取矩阵数组。
领取专属 10元无门槛券
手把手带您无忧上云