gpt4 book ai didi

java - 从逗号分隔的文本文件中读取数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:38 27 4
gpt4 key购买 nike

想要在逗号分隔的文本文件中打印出矩阵,但此代码将打印出全零的矩阵,这不是文本文件中的矩阵。

public int[][] readFromFile() throws FileNotFoundException {
Scanner in = new Scanner(new File("C:\\Users\\Aidan\\Documents\\NetBeansProjects\\matrix\\src\\matrix\\newfile"));
int[][] a = new int[9][9];
while (in.hasNext()) {
String word = in.next();
if (word.equals(",")) {
continue;
}
System.out.println(word);
int x = 0;
int y = 0;
//System.out.println(Integer.parseInt(word));
int s = Integer.parseInt(word);
a[x++][y++] = s;
}
return a;
}

最佳答案

假设您的 csv 文件中有多行:

1,2,3,4,5,6,7,8,9
2,3,4,5,6,7,8,9,1
3,4,5,6,7,8,9,1,2
...

您应该能够执行以下操作:

int[][] a = new int[9][9];
Scanner in = new Scanner(new File("C:\..."));
for (int i = 0; i < 9; i++) {
String[] line = in.nextLine().split(",");
for (int j = 0; j < 9; j++) {
a[i][j] = Integer.parseInt(line[j]);
}
}

这是最低要求,不包括错误检查,如果 csv 中的一行少于 9 个逗号分隔的数字,程序将崩溃。

关于java - 从逗号分隔的文本文件中读取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952240/

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