我正在尝试读取这样的 csv 文件:
0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0,
0, 1, 2, 1, 0, 0, 1, 0,
1, 1, 0, 0, 10, 0,
0, 0, 0, 0, 0, 1, 1, 2, 1, 0,
0, 0, 0, 1, 0, 0, 0,
然后转换成整数格式并对每一行求和,但不知道为什么会出错,我的预期结果应该是这样的:
[exam 1][LWD 5]
[exam 2][LWD 5]
[exam 3][LWD 12]
[exam 4][LWD 5]
[exam 5][LWD 1]
这是我的 java 编码,我使用的是 CSVReader 库:
public static void main(String[] args) throws IOException {
//read text file
CSVReader a = new CSVReader(new FileReader("test.txt"));
//store text data into arraylist
List<String[]> aa = a.readAll();
//create 2D array LWD
int LWD[][] = new int[aa.size()][2];
//store data to array LWD
for (int i = 0; i < aa.size(); i++) {
for (int x = 0; x < aa.get(i).length; x++) {
LWD[i][1] += Integer.parseInt(aa.get(i)[x].trim());
}
LWD[i][0] = i+1;
}
//display LWD
for (int i = 0; i < aa.size(); i++) {
System.out.print("[exam " + LWD[i][0] + "]");
System.out.print("[LWD " + LWD[i][1] + "]");
System.out.print("\n");
}
}
这是我得到的错误结果:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at test.Test.main(Test.java:20)
Java Result: 1
最佳答案
问题似乎是 CSVReader 由于尾随逗号而在每行末尾给出一个空字符串。
例如,当我运行您的确切代码时,但像这样从 csv 文件中删除尾随逗号:
0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0
0, 1, 2, 1, 0, 0, 1, 0
1, 1, 0, 0, 10, 0
0, 0, 0, 0, 0, 1, 1, 2, 1, 0
0, 0, 0, 1, 0, 0, 0
它给出了正确的输出。
我想您可以通过跳过每个字符串数组中的最后一个字符串或更改 csv 文件来解决这个问题
编辑:
这是一个应该适用于当前 csv 格式的快速修复:
public static void main(String[] args) throws IOException {
//read text file
CSVReader a = new CSVReader(new FileReader("test.txt"));
//store text data into arraylist
List<String[]> aa = a.readAll();
//create 2D array LWD
int LWD[][] = new int[aa.size()][2];
//store data to array LWD
for (int i = 0; i < aa.size(); i++) {
for (int x = 0; x < aa.get(i).length-1; x++) {
LWD[i][1] += Integer.parseInt(aa.get(i)[x].trim());
}
LWD[i][0] = i+1;
}
//display LWD
for (int i = 0; i < aa.size(); i++) {
System.out.print("[exam " + LWD[i][0] + "]");
System.out.print("[LWD " + LWD[i][1] + "]");
System.out.print("\n");
}
}
我只更改了第 10 行,用于 (int x = 0; x < aa.get(i).length-1; x++)
已更改 x < aa.get(i).length
至 x < aa.get(i).length - 1
检查字符串是否为空可能更优雅,您可能希望根据 csv
的其余部分来执行此操作文件。
关于Java读取文本并将文本数据作为整数进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719165/