gpt4 book ai didi

java - 需要帮助读取文本文件

转载 作者:行者123 更新时间:2023-12-02 10:43:02 24 4
gpt4 key购买 nike

到目前为止,我已经开发了一个程序,该程序使用邻接矩阵来使用链接实现构建图形。

我一直困惑于如何读取包含邻接矩阵的文本文件,并使用该数据而不是手动输入邻接矩阵。

例如,包含以下内容的文本文件:

4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1
6
0 1 0 1 1 0
1 0 0 1 1 0
0 0 1 0 0 1
0 0 0 0 1 0
1 0 0 0 0 0
0 0 1 0 0 1
3
0 1 1
1 0 1
1 1 0

最佳答案

您可以使用此方法从文件中读取矩阵数据。此方法返回包含零和一的二维字节数组。

public static void main(String[] args) throws IOException {
byte[][] matrix = getMatrixFromFile("matrix.txt");

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + ((j + 1) == matrix[i].length ? "" : " "));
}
System.out.println();
}
}

public static byte[][] getMatrixFromFile(String filename) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filename));
int size = Byte.parseByte(lines.get(0));
byte[][] matrix = new byte[size][size];
for (int i = 1; i < lines.size(); i++) {
String[] nums = lines.get(i).split(" ");
for (int j = 0; j < nums.length; j++) {
matrix[i - 1][j] = Byte.parseByte(nums[j]);
}
}

return matrix;
}

这里我假设文件将包含一个矩阵的数据,如下所示,但我的代码可以轻松扩展以读取多个矩阵的数据并返回二维字节数组的列表。

4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1

关于java - 需要帮助读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796017/

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