把scanner在txt文件中查询到的值放到矩阵中该怎样实现
时间: 2024-05-09 12:20:51 浏览: 7
可以使用二维数组来存储矩阵,先读取txt文件中的行数和列数,然后根据行列数创建一个对应大小的二维数组,再使用Scanner逐行读取txt文件中的值,将其转换为对应的数据类型后存储到二维数组中。以下是一个示例代码:
```
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
// 读取txt文件
File file = new File("matrix.txt");
Scanner scanner = new Scanner(file);
// 读取矩阵的行数和列数
int rows = scanner.nextInt();
int cols = scanner.nextInt();
// 创建二维数组
int[][] matrix = new int[rows][cols];
// 逐行读取txt文件中的值,存储到二维数组中
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
// 输出二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
假设matrix.txt文件内容如下:
```
3 4
1 2 3 4
5 6 7 8
9 10 11 12
```
运行上述代码会输出如下结果:
```
1 2 3 4
5 6 7 8
9 10 11 12
```