4

我的代码是这样的:

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);
        }
    }
}

词组类:

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它不是空的,因为它在 Main 中定义了一个字符串。

4

1 回答 1

11

因为每个对象的默认值(参见默认值部分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();
}
于 2013-11-10T18:52:22.437 回答