我尝试运行此程序时导致java.lang.NullPointerException错误的原因是什么?

时间:2013-11-10 18:51:09

标签: java arrays

我的代码是:

public class Main{

    public static void main(String[] args){
        WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
        WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");

        String[] quoteOne = wordgroupOne.getWordArray();   
        String[] quoteTwo = wordgroupTwo.getWordArray();

        for (String word : quoteOne){
            System.out.println(word);
        }

        for (String word : quoteTwo){                       
            System.out.println(word);
        }
    }
}

Wordgroup类:

public class WordGroup {
    public String words;

    public WordGroup (String getWords){
        words = words.toLowerCase();
    }

    public String[] getWordArray(){
        return words.split(" ");   
    }
}

它编译得很好,但是当我尝试运行它时,我收到错误java.lang.NullPointerException并突出显示“words = words.toLowerCase();”(我正在使用blueJ)是什么导致了这个?

研究它时说这个错误是当你尝试操作一个空集时,WordGroup不是null,因为它有一个在Main中定义的字符串。

1 个答案:

答案 0 :(得分:11)

因为每个对象的默认值(请参阅default value section)为null。由于您没有初始化words,因此会抛出NPE。

public WordGroup (String getWords){
   words = words.toLowerCase(); <- here words is null so a NPE is thrown
}

但我认为你没有正确设置你的构造函数;它应该是:

public WordGroup (String getWords){
   words = getWords.toLowerCase();
}