【发布时间】:2014-06-03 17:03:10
【问题描述】:
我想知道是否有人可以帮助我找出这个空指针异常。我正在制作一个程序来查找英语单词的所有字谜。我创建了一个类EnglishDictionary,当给定一个英语单词的长度及其第一个字母时,它会扫描一个包含所有英语单词的文本文件,然后选择将长度相同且包含第一个字母的单词添加到ArrayList。代码如下:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
public class EnglishDictionary {
public EnglishDictionary(String firstLetter, int wordLength) {
ArrayList<String> words = new ArrayList<String>();
processDict(firstLetter, wordLength);
}
public void processDict(String firstLetter, int wordLength) {
try {
FileReader fReader = new FileReader("englishWords.txt");
BufferedReader reader = new BufferedReader(fReader);
while (true) {
String line = reader.readLine();
if (line == null) {
break;
} else {
if (line.length() == wordLength) {
words.add(line);
}
}
}
} catch (IOException e) {
System.out.println("File does not exist.");
}
}
public ArrayList<String> getWords() {
return words;
}
public void printWords() {
for (String word : words) {
System.out.println(word);
}
}
private ArrayList<String> words;
}
如您所见,我还没有添加检查第一个字母是否在所选英文单词中的功能。当我从另一个类创建 EnglishDictionary 对象时,我得到一个空指针异常。它说:
Exception in thread "main" java.lang.NullPointerException
at EnglishDictionary.processDict(EnglishDictionary.java:23)
at EnglishDictionary.<init>(EnglishDictionary.java:10)
at Main.main(Main.java:6)
我似乎无法弄清楚这是从哪里来的。其他人能看到吗?提前致谢。
【问题讨论】:
-
一个好的答案不值得任何投票。这几天发生了什么。