2012-01-26 76 views
1

这里我正在读取每行中包含整数的文本文件,并且打印出现多次出现的所有整数。从文本文件中读取时的数字格式异常

正如你所看到的我使用哈希映射和我分配整数作为键和数量作为值的出现次数。

这里我在这里得到数字格式异常。谁能帮我这个?

package fileread; 

import java.io.*; 
import java.util.HashMap; 


public class Main { 


public static void main(String[] args) { 
    // TODO code application logic here 
    HashMap<Integer, Integer> lines = new HashMap<Integer, Integer>(); 
    try { 
     FileInputStream fstream = new FileInputStream("C:/Users/kiran/Desktop/text.txt"); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String str; 

     while ((str = br.readLine()) != null) { 

      Integer intObj = Integer.valueOf(str); 
      if (lines.containsKey(intObj)) { 
       int x = 0; 
       x = lines.get(intObj); 
       if (x == 2) { 
        System.out.println(intObj); 
       } 
       lines.put(intObj, x++); 

      } else { 

       lines.put(intObj, 1); 
      } 
     } 
     in.close(); 
    } catch (Exception e) { 
     System.err.println(e); 
    } 
} 
} 
+0

异常消息将显示它试图解析为整数。 – hmjd

+1

'DataInputStream'是必需的吗?那可能会导致这个问题? –

+1

@ nicholas.hauschild是的,DataInputStream似乎没有必要。你应该能够将'fstream'直接传递给'BufferedReader'构造函数。 –

回答

3

这很可能是你的数字格式的例外是在这条线发生的事情:

  Integer intObj = Integer.valueOf(str); 

查看文档Integer.valueOf这里

我猜这是因为线路之一不是一个整数

+1

这是唯一可以抛出异常的地方。它可能与文件末尾的额外空行一样简单。在这条线上放置一个断点(或者甚至是println)来检查'str'的值会将罪犯揪出来。 –

+0

@Rodney Gitzel:你是对的.. –

3

对于调试,我想我会建议在循环开始处添加类似于此行的东西:

System.out.println("str = \"" + str + "\"");

我在代码中看到,你会得到一个NumberFormatException异常是从Integer.valueOf唯一的地方。我的猜测是,你收到一些空格或其他东西到str,当你尝试将它格式化为数字时,它失败了。

另外,如果你想尝试捕捉时,它的发生,你可以尝试围绕Integer.valueof添加一个try/catch这样的:

Integer intObj = null; 
try 
{ 
    intObj = Integer.valueOf(str); 
} 
catch(NumberFormatException nfe) 
{ 
    System.err.println("The value \"" + str + "\" is not a number!"); 
} 

祝你好运!

2

在提供str作为valueOf()方法的参数之前,请尝试使用trim()方法。

str = str.trim(); 
Integer intObj = Integer.valueOf(str); 

而且,因为你正在使用的文件输入/输出,为什么不使用java.nio包,而不是使用旧java.io包。 java.nio对这种工作更好。请仔细阅读此处comparison b/w java.nio and java.io

希望这可能有助于某种方式。

Regards

+0

提及修剪+1。文件中的非打印字符比我曾经关心的承认更多的文件扫描。 – Perception

+0

@Perception:我也有同样的担忧:-) Thankyou和问候 –

相关问题