Java 使用二叉树节点的while循环中的NullPointerException

Java 使用二叉树节点的while循环中的NullPointerException,java,eclipse,nullpointerexception,while-loop,binary-tree,Java,Eclipse,Nullpointerexception,While Loop,Binary Tree,我在这里使用的是二叉树结构。我从包含while语句的行中得到一个“NullPointerException”。我完全不明白为什么会这样 BinaryTreeNode<CharData> currNode = theTree.findValue(data); // Move up the Binary Tree to create code. while(currNode.getParent() != null) { // The loop d

我在这里使用的是二叉树结构。我从包含while语句的行中得到一个“NullPointerException”。我完全不明白为什么会这样

   BinaryTreeNode<CharData> currNode = theTree.findValue(data);

    // Move up the Binary Tree to create code. 
    while(currNode.getParent() != null) {
        // The loop does some stuff that doesn't
        // affect what is assigned to currNode.

        // Move to the parent node for the next iteration.
        currNode = currNode.getParent();

    } // End the while loop.

    return code; // Return the string of binary code.
BinaryTreeNode currNode=tree.findValue(数据);
//向上移动二叉树以创建代码。
while(currNode.getParent()!=null){
//循环做了一些不需要的事情
//影响分配给节点的内容。
//移动到父节点以进行下一次迭代。
currNode=currNode.getParent();
}//结束while循环。
返回代码;//返回二进制代码的字符串。

Find value是我的BinaryTree类中的一个方法,它搜索并查找包含特定数据的节点。我知道这可以通过在这个实现之外单独测试它来实现

while循环语句可以抛出
NPE
的唯一原因是,当
currNode
null
时。我怀疑
findValue()
返回了
null

我想一个解决方案(当您关心最顶端的节点时)是:

while(currentNode != null) {
    rootNode = currentNode;
    currentNode = currentNode.getParent();
}
或依赖布尔快捷方式求值的典型模式:

while(curentNode != null && currentNode.getParent() != null) 
或者我喜欢的使用防护装置的解决方案:

if (currentNode == null)
   throw NotFound(); // or return something

while(curentNode.getParent() != null) {
如果您看到代码:

BinaryTreeNode<CharData> currNode = theTree.findValue(data);

无论如何,
currNode
null
,因此您的
findValue(…)
方法有问题。当找不到值时,findValue返回什么?1)是否有可能
findValue
返回
null
和2)如果找不到
数据怎么办?那不会返回空值吗?我想出来了。在花了大约一个小时思考之后,我决定发布。大约五秒钟后,我明白了。我必须为这个类添加另一个findValue方法,因为在这个类中,我使用数据类型CharData实现BinaryTreeNodes。问题是我创建了一个新的CharData对象来传递给findValue方法,所以java说这个对象和那个对象不“相等”,尽管它们可能包含相同的值。我必须创建一个findValue方法,专门在其CharData中找到具有特定char值的节点。当我试图找到一个简单的整数或字符时,我的findValue()方法起作用了,没什么特别的。在本例中,我试图找到包含CharData对象的节点,该对象是我用字符创建的类,以及它在给定字符串中出现的次数。通过尝试使用findValue(),我让java搜索一个从技术上讲在二叉树中不存在的对象,因为我创建了一个新的实例来传递给findValue()方法。我创建了一个与findValue()基本相同的类,但考虑了CharData类型。看看我上面的评论。
while(currNode != null  && currNode.getParent != null) {
   // your code here
}