我不斷得到一個我的字符串,我不知道為什么。編譯時它似乎工作正常,我無法找出代碼的錯誤導致它無法運行。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]);
}

aluckdog
TA貢獻1847條經驗 獲得超7個贊
問題是你正在閱讀一整行。
while ((line = br.readLine()) != null)
不能基于帶有空格的整行來分析整數。
您有兩種選擇:
在調用方法并按空格拆分它之前,請先閱讀該行,然后將其傳遞到方法中。
String[]
loadArray
省略該參數并按空格拆分行。然后,您可以循環訪問該數組的內容,并根據需要將每個內容轉換為 int。
loadArray
添加回答
舉報
0/150
提交
取消