use*_*031 0 java nullpointerexception
我想知道有人可以帮我找出这个空指针异常.我正在制作一个程序来查找英语单词的所有字谜.我创建了一个类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;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我还没有添加检查第一个字母是否在所选英语单词中的功能.当我从另一个类创建一个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)
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄清楚这是从哪里来的.其他人可以看到吗?提前致谢.
words
没有正确初始化.您正在初始化隐藏CLASS变量字的LOCAL变量字.
在您的构造函数中执行此操作:
public EnglishDictionary(String firstLetter, int wordLength) {
//ArrayList<String> words = new ArrayList<String>(); // Creates a local variable called 'words'; class member does NOT get initialized.
words = new ArrayList<String>(); // THIS initializes the class variable.
processDict(firstLetter, wordLength);
Run Code Online (Sandbox Code Playgroud)
}