2013-04-25 694 views
2

我有以下代碼:無限遞歸

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設置新節點的深度。

由於某些原因,它似乎會生成無限遞歸,但是......有什麼建議嗎?

+0

您是否嘗試過使用print語句來獲得深度的價值?或者使用調試器?如果每個子層的深度沒有增加1,那麼這將解釋無限遞歸。 – Patashu 2013-04-25 23:38:45

+0

什麼是MAX_DEPTH?定義無限遞歸 - 它只是一直持續下去,還是拋出StackOverflowException? – Dukeling 2013-04-25 23:42:12

+0

Dukeling我已經將MAX_DEPTH設置爲2,並且它似乎只是永遠。事實上,在2級時,不需要檢查超過36個案例...... – MrD 2013-04-25 23:43:11

回答

0

你的問題不是無限遞歸。這可能是別的。此代碼對我的作品 -

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