java - 使用二叉树节点的 while 循环中出现 NullPointerException

标签 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 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.

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

最佳答案

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

我猜一个修复(当你关心最顶层的节点时)是:

while(currentNode != null) {
    rootNode = currentNode;
    currentNode = currentNode.getParent();
}

或者依赖于 boolean 快捷方式评估的典型模式:

while(curentNode != null && currentNode.getParent() != null) 

或者我更喜欢使用守卫的解决方案:

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

while(curentNode.getParent() != null) {

关于java - 使用二叉树节点的 while 循环中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214701/

相关文章:

java - 当我在模拟器中打开此 Activity 时,我收到 NumberFormatException 和 NullPointerException。为什么?

java - 尝试显示图像时出现 NullPointerException?

java - 我的代码中的什么会导致 for 循环提前终止?我在循环中的某个地方缺少 "i"吗?

java - 基于预加载文档的桌面应用程序

java - 等待计时器在 Java 中完成

java - 我应该将测试方法放在单独的类中吗?如果是这样,怎么办?

android - 在我的应用程序中获取其他应用程序(进程)的上下文 : Android

java - Eclipse 在 Debug模式下不显示变量内容?

java - 使用 mysql PrepareStatement 取消引用可能的空指针警告

java - 无法在我的 java 示例中加载照片