首页 > 解决方案 > 如何在第一层类的方法体内使用嵌套类中的方法

问题描述

我正在学习系统工程只有 2 个月,所以请放轻松。我正在开发一个包含列表、堆栈和二叉树的项目。我遇到问题的代码是二叉树内部的代码。

public class BinaryIntTree {


public static class Node {
    
    int value;
    
    The left child.

    Node leftChild;
    
    public int getNodeCount(Node node) {
        if(node == null) {return 0;}
        int counter = 0;
        
        if(node.leftChild == null && node.rightChild == null) {
            return 1;
        } else {
            counter += 1;
            if (node.leftChild != null) {
                counter += getNodeCount(node.leftChild);
            }
            if (node.rightChild != null) {
                counter += getNodeCount(node.rightChild);
            }
        }
        return counter;
    }
    
    
    public Node(int value) {
        this.value = value;
    }

 public int getNodeCount() {
    return root.getNodeCount(root);
}

第二个 getNodeCount() 在 Main 类中,我希望,如果我使用 getNodeCount(),我无法更改用作起点的 Object(root)。所以我认为 id 只是在嵌套的 Node 类中实现它,并让它在 Main 类的 Method 中调用。

但它抛出了一个 NullPointerException,应该用 if(node == null) {return 0;} 解决它,但它没有。提前感谢您的帮助,也请不要对方法本身发表评论,因为我想自己解决递归方法。

标签: javaclassmethodsnested

解决方案


getNodeCount将 aNode作为参数,并且不使用Node它被调用的实例(即 the this),这意味着它可能应该是static. 一旦你把它变成静态的,你可以在没有实例的情况下调用它,从而避免NullPointerException你遇到:

public int getNodeCount() {
    return Node.getNodeCount(root);
}

推荐阅读