2013-03-13 78 views
0

我收到以下警告Eclipse的警告

Null passed for nonnull parameter of new java.util.Scanner(Readable) in  
    model.WordCount.getFile(File). 

为什么会出现这一点,我怎么摆脱这个警告?下面是方法:

/** 
    * Receives and parses input file. 
    * 
    * @param the_file The file to be processed. 
    */ 
    public void getFile(final File the_file) { 
    FileReader fr = null; 
    try { 
     fr = new FileReader(the_file); 
    } catch (final FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    Scanner input = null; 
    String word; 
    input = new Scanner(fr); 
    while (input.hasNext()) { 
     word = input.next(); 
     word = word.toLowerCase(). 
      replaceAll("\\.|\\!|\\,|\\'|\\\"|\\?|\\-|\\(|\\)|\\*|\\$|\\#|\\&|\\~|\\;|\\:", ""); 
     my_first.add(word); 
     setCounter(getCounter() + 1); 
    } 
    input.close(); 
    } 

我不得不初始化FileReader为null,以避免错误。这是触发警告的原因。

回答

1

如果线路

fr = new FileReader(the_file); 

抛出一个异常,那么fr保持为空,将肯定不会在扫描仪的工作。这就是警告的内容。

它基本上告诉你,打印异常的堆栈跟踪没有正确的错误处理。相反,如果出现早期例外情况,您应该考虑退出该方法。或者,您可能希望将异常处理块放在方法的所有代码中,而不是围绕单一行。然后警告也将消失,因为例外将导致在方法中不执行任何进一步的代码。

+0

谢谢!这非常有帮助。 – 2013-03-13 06:19:04