2016-10-21 96 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”,“”)或解析线与正则表达式