尽管检查

时间:2017-03-03 05:54:04

标签: java eclipse java-ee

我正在尝试为每个具有模式的单词构建二进制树(ex hello - pattern是ABCCD)

我一直在它所声明的行上得到一个空指针异常

    while(pos.getPattern() != null || a){

我不明白为什么 - 有检查到位。另外,当我打印pos.getPattern()时 - 我得到的字符串不是空值

我真的可以使用一些帮助

public void AddWord(String word) {
    TreeNode pos = root;
    boolean a = true;
    String pat = PatternMaker.MakePattern(word);
    while(pos.getPattern() != null || a){

        if (pos.getPattern().equals(pat)) {
            WordList list = pos.getList();
            list.insertWord(word);
            pos.setList(list);
            a = true;
        } else if (pat.compareTo(pos.getPattern()) > 0) {
            pos = pos.getRight();
        } else {
            pos= pos.getLeft();

        }
    }
    if(pos ==null){
        pos = new TreeNode(word, pat);
    }
}

3 个答案:

答案 0 :(得分:2)

您需要在null循环中添加pos检查while

某些时候pos将在null循环内成为while

public void AddWord(String word) {
    TreeNode pos = root;
    boolean a = true;
    String pat = PatternMaker.MakePattern(word);
    while((pos!=null && pos.getPattern() != null) || a){

        if (pos.getPattern().equals(pat)) {
            WordList list = pos.getList();
            list.insertWord(word);
            pos.setList(list);
            a = true;
        } else if (pat.compareTo(pos.getPattern()) > 0) {
            pos = pos.getRight();
        } else {
            pos= pos.getLeft();

        }
    }
    if(pos ==null){
        pos = new TreeNode(word, pat);
    }
}

希望这有帮助!

答案 1 :(得分:0)

您的代码有一行pos = pos.getLeft()。如果该方法返回null,则调用pos.getPattern()将抛出NPE。

答案 2 :(得分:0)

null值检查树的节点是否为空。您可以表示任何值来表示空节点,但它不应与字符串的值重叠。如果您的集合必须是某种其他语言的String类型,则可以使用空字符串""来表示空值。建议将值保留为null,因为它可以避免初始化成本并使检查运行更快。

正如@Teto解释的那样,getPattern会将空指针抛出空字符串。

相关问题