为什么我会得到一个nullpointer异常? (初学者)

时间:2016-11-13 06:37:54

标签: java eclipse

我对此非常沮丧,并且已经尝试了几天尝试修复它。我有两个类,Main和GetNounList

主要:

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

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
    GetNounList nouns = new GetNounList();

}// end main method
}//end of Main class

GetNounList:

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

public class GetNounList extends Main {
ArrayList<String> listOfWords;

public GetNounList() throws FileNotFoundException {
    Scanner list = new Scanner(new File(
    "/Users/FareedMabrouk/Desktop/Explore/Coding/Java/BusinessIdeaGenerator/CodeRepository/BusinessGen/src/Nouns.txt"));

while (list.hasNextLine()) {
        listOfWords.add(list.nextLine());
    } // end while loop
    System.out.println(listOfWords);
}//end constructor
}//end GetNounList class

该文件包含这样的随机名词:

cat
laptop
dog
headphones

等...

唯一的错误是在将文件中的名词添加到arraylist的行处的nullpointer异常。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

listOfWords从未构建过。

替换

ArrayList<String> listOfWords;

List<String> listOfWords=new ArrayList<>();