2016-10-21 97 views
-1

這是我所做的代碼的一部分。 閱讀器似乎讀取第一個字符串「2」,但由於某些原因它不會將其轉換爲整數。閱讀時出現Java NumberFormatException

public void fileinput2() 
{ 
try 
{ 
     BufferedReader file=new BufferedReader(new FileReader("ddv.txt")); 
     try 
{ 
      while((line=file.readLine())!=null){ 
       String[] s=line.split("\\t+"); 
       int firstindex=Integer.parseInt(s[0].trim()); 
       int secondindex=Integer.parseInt(s[1].trim()); 
            adj[firstindex-1][secondindex-1]=1; 
       adj[secondindex-1][firstindex-1]=1; 
            /*for(int i=0;i<s.length;i++) 
            {System.out.println(s[i]); 
            int x=Integer.valueOf(s[i].trim()); 
            }*/ 

       } 
     } catch (NumberFormatException | IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

的DDV是一個文本文件,該文件是這樣的:

2 8 
6 9 
4 10 

等。

但是我得到這個錯誤

java.lang.NumberFormatException: For input string: "2" 
at  
    java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 

at java.lang.Integer.parseInt(Integer.java:580) 
at java.lang.Integer.parseInt(Integer.java:615). 

請幫我謝謝你。:)

+0

看看HTTP ://stackoverflow.com/a/3762377/4626402 – Abhishek

回答

0

更改定界符@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表示而不是/ t(line.split(「\ t」);)。此外,您需要添加驗證檢查,您讀取的每一行實際上是整數

0

它不是真正的「2」,在「2」之前有不可打印的符號\ uFEFF。它是在你的文件不可見的UTF-8字頭

您可以分析文件的第一個字符或只加懶s.replace(「\ uFEFF」,「」)或解析線與正則表達式