-3 java parseint numberformatexception
所以我有这段代码从csv文件中读取文本,其中nums []遍历整个文件并存储所述学生的编号,并且成绩[] []通过并存储他们的每个成绩:
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] stuff = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
stuff[i] = line.split.(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(stuff[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<11; y++){
grades[x][y] = Integer.parseInt(stuff[x][y]);
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于麻木效果很好,但是成绩不能存储超过第一列数据的任何值.如果我设置等级[x][y] = stuff[any number] [0]它将运行,但如果我尝试在行中超过0,我会错误终止.
部分数据文件:
1, 66, 82, 85, 87, 65, 80, 97, 75, 68, 72
2, 70, 63, 75, 62, 84, 65, 67, 95, 81, 96
3, 100, 98, 73, 78, 69, 75, 97, 66, 61, 90
4, 75, 62, 79, 78, 87, 73, 74, 76, 63, 84
5, 81, 90, 80, 66, 75, 96, 73, 77, 66, 87
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:java.lang.NumberFormatException:对于输入字符串:"66"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
在java.lang.Integer.parseInt(Integer.java:481)
在java.lang.Integer.parseInt(Integer.java:527)
固定代码(我道歉,我没有逐字复制代码并在其中包含一些额外的错误)
public static void main(String [] args)抛出FileNotFoundException
{
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] values = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
values[i] = line.split(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(values[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<10; y++){
grades[x][y] = Integer.parseInt(values[x][y+1].trim());
}
}
Run Code Online (Sandbox Code Playgroud)
你没有摆脱令牌之间的空白.
确保清除它,最好用 String#trim()
Integer.parseInt(stuff[x][0].trim());
Run Code Online (Sandbox Code Playgroud)
为了记录,我还希望使用比名称更好的名字stuff.