本質上,該程序的目的是將學生信息寫入文件并從同一文件中讀取。該程序包含一個 if 語句,用于判斷學生是否處于良好的信譽或學術試用期,每個文件都有各自的文件(goodstanding.txt 和 probation.txt)。如果我注釋掉 goodstanding.txt 的讀取邏輯,程序工作文件,但對我來說,除了文件路徑之外,它們似乎幾乎相同,顯然。我查看了其他問題,但其中大多數似乎與錯誤的類型轉換有關。它拋出的具體錯誤NumberFormatException For input string: ""在線ID = Integer.parseInt(array[0]);寫邏輯如下:if(GPA >= 2.0) //If GPA >= 2.0, write to good standing file. This is identical to probation writer, but causes an issue somewhere{ String result = ID + "," + fname + " " + lname + "," + GPA; OutputStream out = new BufferedOutputStream(Files.newOutputStream(good, StandardOpenOption.CREATE)); BufferedWriter wt = new BufferedWriter(new OutputStreamWriter(out)); wt.write(result, 0, result.length()); //Write to file from position 0 to length wt.newLine(); System.out.println("Please enter next WIN or 999 to quit: "); ID = input.nextInt(); input.nextLine(); wt.close();} if(GPA < 2.0) //If GPA < 2.0, write to probation file { String result = ID + "," + fname + " " + lname + "," + GPA; OutputStream out = new BufferedOutputStream(Files.newOutputStream(probation, StandardOpenOption.CREATE)); BufferedWriter wt = new BufferedWriter(new OutputStreamWriter(out)); wt.write(result, 0, result.length()); wt.newLine(); System.out.println("Please enter next WIN or 999 to quit: "); ID = input.nextInt(); input.nextLine(); wt.close();}和讀取邏輯:try{ while(line != null){ array = line.split(","); ID = Integer.parseInt(array[0]); name = array[1]; GPA = Double.parseDouble(array[2]); double ahead = GPA - 2; System.out.println("WIN: " + ID + " | " + " Name: " + name + " |" + " GPA = " + GPA + " | Ahead by " + ahead); line = reader.readLine(); }}我也嘗試在 ID 上使用 trim() 方法,但異常仍然存在。是否有一個我需要閱讀更多的概念來解釋這一點?
1 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
我認為錯誤消息很清楚NumberFormatException For input string: "",因為您無法將空字符串解析為int。
您的問題至少有兩個原因,或者您的文件中有一些空白行,或者您的其中一行以逗號開頭。通過執行以下操作來檢查或忽略此類行:
....
while (line != null) {
if(!line.startsWith(",") && !line.isEmpty()){
array = line.split(",");
ID = Integer.parseInt(array[0]);
name = array[1];
GPA = Double.parseDouble(array[2]);
double ahead = GPA - 2;
System.out.println("WIN: " + ID + " | " + " Name: " + name + " |" + " GPA = " + GPA + " | Ahead by " + ahead);
}
line = reader.readLine();
}
添加回答
舉報
0/150
提交
取消