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

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

為什么我不斷收到一個 java.lang.數字格式例外,盡管它編譯正確?

為什么我不斷收到一個 java.lang.數字格式例外,盡管它編譯正確?

慕沐林林 2022-09-28 09:47:50
我不斷得到一個我的字符串,我不知道為什么。編譯時它似乎工作正常,我無法找出代碼的錯誤導致它無法運行。NumberFormatException這是顯示內容的屏幕截圖。https://imgur.com/a/LfM5SDA如上所述,我找不到我的代碼不起作用的任何原因。對我來說,這一切都是正確的,并且運行良好,直到最后幾種方法出現。public static int loadArray(int[] numbers) {        System.out.print("Enter the file name: ");        String fileName = keyboard.nextLine();        File file = new File(fileName);        BufferedReader br;        String line;        int index = 0;            try {                br = new BufferedReader(new FileReader(file));                while ((line = br.readLine()) != null) {                    numbers[index++] = Integer.parseInt(line);                    if(index > 150) {                        System.out.println("Max read size: 150 elements. Terminating execution with status code 1.");                        System.exit(0);                    }                }            } catch (FileNotFoundException ex) {                System.out.println("Unable to open file " + fileName + ". Terminating execution with status code 1.");                System.exit(0);            }catch(IOException ie){                System.out.println("Unable to read data from file. Terminating execution with status code 1.");                System.exit(0);            }            return index;    }我想使用我的開關能夠在數組中找到不同的值,但我甚至無法正確加載數組文件。
查看完整描述

2 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

在應用工作期間,你將獲得“數字格式異?!?,因為這是運行時異常,它旨在正常工作。


您的解決方案的問題,您嘗試從文件中的整行解析int。


“123, 23, -2, 17” 不是一個整數。因此,您應該執行以下操作:numbers[index++] = Integer.parseInt(line);


String[] ints = line.split(", ");

for(i = 0; i < ints.length; i++ ){

 numbers[index++] = Integer.parseInt(ints[i]);

}


查看完整回答
反對 回復 2022-09-28
?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

問題是你正在閱讀一整行。

 while ((line = br.readLine()) != null)

不能基于帶有空格的整行來分析整數。

您有兩種選擇:

  • 在調用方法并按空格拆分它之前,請先閱讀該行,然后將其傳遞到方法中。String[]loadArray

  • 省略該參數并按空格拆分行。然后,您可以循環訪問該數組的內容,并根據需要將每個內容轉換為 int。loadArray


查看完整回答
反對 回復 2022-09-28
  • 2 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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