亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

順序讀取文件時出現 NumberFormatException?

順序讀取文件時出現 NumberFormatException?

陪伴而非守候 2022-10-12 10:08:21
本質上,該程序的目的是將學生信息寫入文件并從同一文件中讀取。該程序包含一個 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();

    }


查看完整回答
反對 回復 2022-10-12
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號