gpt4 book ai didi

java - 如何将文本文件中的整数读入二维数组?

转载 作者:行者123 更新时间:2023-12-01 18:16:26 25 4
gpt4 key购买 nike

我的文本文件中有整数,所有整数均以空格分隔。

我知道如何读取文件,但不知道如何将整数放入数组中。我知道我必须在某个地方使用 parseInt

该阵列是 4x4。整数是:

2 1 4 2  
9 7 5 3
9 8 3 5
1 0 0 0

我的代码:

arr = new int [4][4];
IODialog input = new IODialog();
String location = input.readLine("Enter the full path of the configuration text file: ");
Scanner scn = null;
try {
scn = new Scanner(new BufferedReader(new FileReader(location)));
int i, j = 0;
String line = scn.nextLine();
String[] numbers = line.split(" ");
} finally {
if (scn != null) {
scn.close();
}
}

最佳答案

这会很有帮助,

   int[][] a = new int[4][4];
BufferedReader br = new BufferedReader(new FileReader("path/to/file"));

for (int i = 0; i < 4; i++) {
String[] st = br.readLine().trim().split(" ");
for (int j = 0;j < 4; j++) {
a[i][j] = Integer.parseInt(st[j]);
}
}

关于java - 如何将文本文件中的整数读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com