我收到以下警告
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以避免错误。这就是触发警告的原因。
答案 0 :(得分:1)
如果该行
fr = new FileReader(the_file);
抛出异常,然后fr
保持为空,绝对不会在扫描程序中起作用。这就是警告的内容。
它基本上告诉你打印异常的堆栈跟踪是没有正确的错误处理。相反,你应该考虑在早期异常的情况下退出方法。或者,您可能希望将异常处理块放在方法的所有代码周围,而不仅仅是围绕该单行。然后警告也将消失,因为例外将导致不在该方法中执行任何进一步的代码。