gpt4 book ai didi

java - 如何在 Java 中将数字文件读入数组列表

转载 作者:行者123 更新时间:2023-12-02 03:42:01 25 4
gpt4 key购买 nike

我希望能够从类似以下内容的文件中读取 map :

0, 0, 0, 0, 0

0, 0, 1, 0, 0

0, 1, 1, 1, 1

0, 1, 1, 1, 0

0, 0, 1, 1, 0

并创建一个如下所示的数组列表:

{[0, 0, 0, 0, 0],

[0, 0, 1, 0, 0],

[0, 1, 1, 1, 1],

[0, 1, 1, 1, 0],

[0, 0, 1, 1, 0]}

我尝试过使用 br.readLine() 但它似乎被卡住了,但没有在中间抛出错误。

public static int[][] loadFile() throws IOException{

    FileReader in = new FileReader(Main.currentFilePath + Main.currentFile);
BufferedReader br = new BufferedReader(in);
String line;
int [] intArray = {};
int [][] fileArray = {};
int j = 0;
while ((line = br.readLine()) != null) {
List<String> stringList = new ArrayList<String>(Arrays.asList(line.split(",")));
String[] stringArray = stringList.toArray(new String[0]);
List<Integer> intList = new ArrayList<Integer>();
System.out.println("RRRRR");
for(int i = 0; i < stringList.size(); i++) {
Scanner scanner = new Scanner(stringArray[i]);
System.out.println("GGGGG");
while (scanner.hasNextInt()) {
intList.add(scanner.nextInt());
intArray = intList.parallelStream().mapToInt(Integer::intValue).toArray();
System.out.println("FFFF");
}
System.out.println(fileArray[j][i]);
fileArray[j][i] = intArray[i];
}
j++;
}
return fileArray;

}

最佳答案

基本问题是,您声明了一个 0 长度的数组(无元素),这使得无法向其中添加任何元素。

int [][] fileArray = {};

除非您事先确切地知道所需的行/列数,否则数组不是很有帮助,相反,您可以使用某种List,例如...

List<int[]> rows = new ArrayList<>(5);
int maxCols = 0;
try (BufferedReader br = new BufferedReader(new FileReader(new File("Test.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
String[] parts = text.split(",");
int[] row = new int[parts.length];
maxCols = Math.max(maxCols, row.length);
for (int col = 0; col < parts.length; col++) {
row[col] = Integer.parseInt(parts[col].trim());
}
rows.add(row);
}
} catch (IOException ex) {
ex.printStackTrace();
}

int[][] map = new int[rows.size()][maxCols];
for (int row = 0; row < rows.size(); row++) {
map[row] = rows.get(row);
}

我的“个人”直觉是根本不用理会数组,只需使用复合List...

List<List<Integer>> rows = new ArrayList<>(5);
try (BufferedReader br = new BufferedReader(new FileReader(new File("Test.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
String[] parts = text.split(",");
List<Integer> row = new ArrayList<>(parts.length);
for (String value : parts) {
row.add(Integer.parseInt(value.trim()));
}
rows.add(row);
}
} catch (IOException ex) {
ex.printStackTrace();
}

关于java - 如何在 Java 中将数字文件读入数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732507/

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