【发布时间】:2014-09-03 08:15:49
【问题描述】:
我正在尝试读取这样的 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
【问题讨论】:
-
在 csv 格式中,您没有空格。你得到了什么错误/结果?
-
确认一下,哪一行代码是第20行?
-
这是第 20 行:LWD[i][1] += Integer.parseInt(aa.get(i)[x].trim());
-
+1 它只是帮助我练习更多的 lambda 表达式
标签: java string csv integer format