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

参见英文答案 > What is a NullPointerException, and how do I fix it?                                    12个
我的代码是这样的:

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中定义的字符串.

最佳答案
因为每个对象的默认值(参见default value section)为null.由于您没有初始化单词,因此会抛出NPE.

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

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

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

转载注明原文:我尝试运行此程序时导致java.lang.NullPointerException错误的原因是什么? - 代码日志