如果文本文件由一行數字組成,下面的代碼可以完全正常運行,但是一旦它到達例如一行說“我是40”,它就會跳過它,而不是將40放入數組中。Scanner inFile = null; File file = null; String filePath = (JOptionPane.showInputDialog("Please enter a file path")); int size = 0; int[] result = new int[10]; try { file = new File(filePath); inFile = new Scanner(file); int skippedCounter = 0; for(int i = 0; inFile.hasNext(); i++){ if(inFile.hasNextInt()) result[i] = inFile.nextInt(); else{ String strOut = ""; String data = inFile.next(); for(int j = 0; j <= data.length() - 1; j++){ if(!Character.isLetter(data.charAt(j))){ strOut += data.charAt(j); } else skippedCounter++; } result[i] = Integer.parseInt(strOut); } } }
3 回答
DIEA
TA貢獻1820條經驗 獲得超3個贊
next()將為您提供下一個令牌,而不是下一行。所以變量可能會超過十。如果你沒有一個空的捕獲,你會意識到這一點:你的數組正在越界i
溶液:
不要使用結果數組,使用結果列表,并在有其他結果時追加到其末尾
注意:
另一個可能發生的隱藏異常是,當您的 parseInt 由于非數字數據而失敗時。因此,不要將所有內容都包裝在巨大的嘗試/捕獲中,這只會使調試變得更加困難!
慕妹3242003
TA貢獻1824條經驗 獲得超6個贊
以下
result[i] = Integer.parseInt(strOut)
將導致 在嘗試處理任何信件時出現 。作為空字符串中的結果NumberFormatExceptionstrOut""
在嘗試解析之前,您必須檢查空字符串
if (!strOut.isEmpty()) {
result[i] = Integer.parseInt(strOut);
}添加回答
舉報
0/150
提交
取消
