有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无限递归

我有以下代码:

public void generateTree(Node myNode) {
    for(int i = 1; i <= 6; i++) {
        //Creating child node
        Node child = new Node();

        //Setting new Depth
        child.setDepth(myNode.getDepth()+1);

        //Adding node to tree
        myTree.add(child);

        //If the game isn't over and we're not reached the maximum depth, recurse
        if(!isGameOver() && child.getDepth() < MAX_DEPTH)
            generateTree(child);
    }
}

其中,MAX_DEPTH基本上是一个整数,表示我想在游戏中探索移动树的最大深度,getDepth()返回作为参数提交的节点的深度,setDepth设置新节点的深度

出于某种原因,它似乎生成了一个无限递归,然而。。。有什么建议吗


共 (1) 个答案

  1. # 1 楼答案

    你的问题不是无限递归。可能是别的原因。这个代码对我有用-

    import java.util.ArrayList;
    import java.util.List;
    
    
    public class Node 
    {
    
        private int depth;
    
        public static final int MAX_DEPTH = 2;
    
        private static List<Node> myTree = new ArrayList<Node>(); // for testing purposes
    
        public void generateTree(Node myNode) {
            for(int i = 1; i <= 6; i++) {
                //Creating child node
                Node child = new Node();
    
                //Setting new Depth
                child.setDepth(myNode.getDepth()+1);
    
                //Adding node to tree
                myTree.add(child);
    
                //If the game isn't over and we're not reached the maximum depth, recurse
                if(child.getDepth() < MAX_DEPTH)
                    generateTree(child);
            }
        }
    
        public static void main(String [] args)
        {
            Node node = new Node();
    
            Node myNode = new Node();
            myNode.setDepth(0);
    
            node.generateTree(myNode);
    
            System.out.println(myTree.size());
    
        }
    
        public int getDepth() {
            return depth;
        }
    
        public void setDepth(int depth) {
            this.depth = depth;
        }
    
    }
    

    我得到的结果是

    42