为什么这个方法抛出空指针异常?

时间:2015-05-06 16:13:22

标签: nullpointerexception trie

我尝试使用addWord方法编写一个类来创建前缀树(或trie),该方法将字符串作为参数并将每个字符存储在树中的适当位置。

但是,我在第一个if语句的行中继续得到NullPointerException(如下所示)。任何人都可以帮助我理解造成这种情况的原因吗?先感谢您!

public class PrefixTree {

    private Node root;

    public PrefixTree () {
        root = new Node();
    }

    public void addWord(String word) {

        int length = word.length();
        char currentCharacter = word.charAt(0);
        Node currentNode = root;

        //Essentially this is saying "for each character in the string..."
        for(int i=0; i<length; i++){

            currentCharacter= word.charAt(i);


            //if the children array of parent node does not contain the current character
            //create a new node and add it to the parent array. 
            //HERE IS WHERE THE EXCEPTION IS BEING THROWN 
            if(currentNode.children[currentCharacter - 'a'] == null) {
            Node newNode = new Node();

            //set the node character value equal to the current character
            newNode.c=currentCharacter;

            //add the new node to the child array of its parent node
            currentNode.children[currentCharacter - 'a']= newNode;

            //if this is the last character in the word, change the endWord value to true
            if( i == length-1) {
                newNode.endWord = true;
                //stores the complete string in its ending node
                newNode.fullWord = word;

            }

            //set current node equal to the new node created and repeat the process
            currentNode = newNode;
        }
    }

}

private class Node {
    public boolean endWord;
    public char c;
    public Node[] children;
    public String fullWord;

    public Node(){
        c = '0'; 
        endWord = false;
        Node[] children = new Node[26];
        //Stores the complete string of a word ending w/ this node to make life easier later
        String fullWord = null;

    }
}

public static void main(String [] args){
    PrefixTree test = new PrefixTree();

    test.addWord("test");




}

}

1 个答案:

答案 0 :(得分:2)

因为您要在Node的构造函数中分配局部变量。改为:

public Node(){
    c = '0'; 
    endWord = false;
    this.children = new Node[26];
    //Stores the complete string of a word ending w/ this node to make life easier later
    this.fullWord = null;
}