簡體   English   中英

從文件讀取時出現java.lang.NumberFormatException

[英]java.lang.NumberFormatException while reading from a file

我正在嘗試創建一個基本程序,它讀取矩陣中排列的未知數量的文件,創建String格式的數組列表以讀取它,然后將其解析為int以便進行其他多個處理。 解析時出現java.lang.NumberFormatException ,我知道它可能是因為將空白值解析為int。 我看過其他問題,但似乎無法解決。 這是代碼的一部分:

public static void main(String[] args) {
    try {
            br = new BufferedReader(new FileReader(theFile));
            String line = null;

            while ((line = br.readLine()) != null) {                
                String[] aLine = line.split("/t");
                br.readLine();
                numLine.add(aLine);
            }
        } catch (IOException e){
        } finally {
            try {
                br.close();
            } catch (Exception e) {
            }
        }

    for (int i=0; i < numLine.size(); i++){
        for (int j = 0; j < numLine.get(i).length; j++){
            System.out.print(numLine.get(i)[j] + " ");
            //  if (!((numLine.get(i)[j]).equals("\t"))){
            intList.add(Integer.parseInt(numLine.get(i)[j]));
            //  }
        }
        System.out.println();
    }
}

這是錯誤的意思:

Exception in thread "main" java.lang.NumberFormatException: For input string: "6    10  9   10  12  "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at readingTextFiles.Main.main(Main.java:34)

請考慮到我是一個新手程序員,所有這些都是從研究中獲得的,所以我不確定該理論是如何工作的。

更改分隔符,如@kayKay所述,您正在嘗試再次讀取該行。 我認為你不應該??

public static void main(String[] args) {
try {
    br = new BufferedReader(new FileReader(theFile));
    String line = null;

    while ((line = br.readLine()) != null) {
        String[] aLine = line.split("\t"); // Also as kaykay mentioned change /t to \t
        //br.readLine();  // You are reading the line again - Comment it out 
        numLine.add(aLine);
    }
} catch (IOException e){
} finally {
    try {
        br.close();
    } catch (Exception e) {
    }
}

for (int i=0; i < numLine.size(); i++){
    for (int j = 0; j < numLine.get(i).length; j++){
        System.out.print(numLine.get(i)[j] + " ");
        //  if (!((numLine.get(i)[j]).equals("\t"))){
        intList.add(Integer.parseInt(numLine.get(i)[j]));
    }
System.out.println();
}

該程序的輸出是什么? 制表符由\\t而不是/tline.split("\\\\t"); )表示。 此外,您將需要添加驗證檢查,以確保您閱讀的每一行實際上都是一個Integer

該錯誤消息表示您嘗試將其解析為整數,例如:

"12abc34d" //<-- bad case - re-consider your approach

或類似的東西:

"   911   " //<-- this can be fixed quickly

,在此處添加trim()

intList.add(Integer.parseInt(numLine.get(i)[j].trim()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM