當我試圖將String的最後部分解析爲整數時,我得到NumberFormatException。例外打印如下:使用Integer.parseInt(String arg)時發生Java NumberFormatException
Exception in thread "main" java.lang.NumberFormatException: For input string: "95
"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at GradeBook.parseDataToStudentArray(GradeBook.java:85)
at GradeBook.main(GradeBook.java:12)
我正在運行一個for循環將一個長字符串分解成多個部分,然後從這些部分創建對象。這裏是方法:
private static Student[] parseDataToStudentArray(String data)
{
Student[] students = new Student[10];
System.out.print(data);
for (int i=0;i<10;i++)
{
String tempStudent = data.substring(0,data.indexOf("\n"));
data=data.substring(data.indexOf("\n")+1);
String firstName= tempStudent.substring(0,tempStudent.indexOf(" "));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
String lastName= tempStudent.substring(0,tempStudent.indexOf(" "));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int hw= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int quiz= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int project= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int midterm= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int finalExam= Integer.parseInt(tempStudent);
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
students[i] = new Student(firstName,lastName,hw,quiz,project,midterm,finalExam);
}
return students;
}
非常感謝你的幫助!
我開始與我是否是System.out.print (數據) 產生
John Smith 92 80 86 76 95
Mary Lamb 66 89 92 100 56
Katy Perry 80 75 89 83 90
Mile Johnson 90 92 95 91 88
Jefferson Hue 75 78 70 82 73
Gabby Alden 83 79 88 94 92
Rubby Barry 89 82 75 90 86
Brian Wilson 78 83 81 89 90
Davis Brown 92 78 50 77 84
Alfred Williams 87 93 67 82 95
是否有一些新興的學生管理行業,或者現在的計算機課程創作者只是懶惰地思考更具創造性的任務?啊,順便說一句,只是說出「出錯」的問題描述不會幫助我們幫助你。 – qqilihq
當你使用你的調試器時,它告訴你有關傳遞給Integer.parseInt的值會給你帶來麻煩嗎? –
你從未聽說過「split」嗎? –