2017-08-09 157 views
1

美好的一天,我正在實施一個八叉樹。但是,當輸入大小超過2時,我一直在收到StackOverflowError。我無法理解爲什麼出現此錯誤。八叉樹八叉堆棧溢出錯誤

octree = new Octree(3, new Point(0,0,0)); 

實例化,其中第一個參數是尺寸和第二參數是根

代碼八叉樹的人口

public void generateList(int num) 
{ 
    for(int i = 0 ; i < num; i++) 
     for (int j = 0 ; j < num; j++) 
      for (int z = 0 ; z < num; z++) 
       if (!(z == j && j == i)) { 
        octree.add_nodes(i,j,z); 
       } 
} 

代碼的八叉樹

的add_nodes
public boolean add_nodes(double x, double y, double z) { 

    boolean success = false; 
    System.out.println(x+","+y+","+z); 
    if (this.i < 8) { 
     if (compare(x, y, z)) { 
      if (root.childPoints == null) { 
       System.out.println("Root is null" + x + " " + y + " " + z); 
      } 

      this.root.childPoints[i] = new Point(x, y, z); 
      this.i++; 
      success = true; 
     } 
    } 

    else if (this.childNodes == null) { 

     this.create_nodes_of_nodes(x, y, z); 

     for (int j = 0; j < 8; j++) { 
      double tempx = this.root.x - root.childPoints[j].x; 
      double tempy = this.root.y - root.childPoints[j].y; 
      double tempz = this.root.z - root.childPoints[j].z; 

      int checker = compareValues(tempx, tempy, tempz); 

      this.childNodes[checker].add_nodes(root.childPoints[j].x, 
        root.childPoints[j].y, root.childPoints[j].z); 

     } 
     root.childPoints = null; 

     double tempx = this.root.x - x; 
     double tempy = this.root.y - y; 
     double tempz = this.root.z - z; 
     int checker = compareValues(tempx, tempy, tempz); 
     this.childNodes[checker].add_nodes(x, y, z); 
     // this.i=0; 
    } 

    else { 

     if (childNodes != null) { 
      int checker = compareValues(x, y, z); 
      childNodes[checker].add_nodes(x, y, z); 

     } 
    } 

    return success; 
} 

錯誤

Exception in thread "main" java.lang.StackOverflowError 
at sun.misc.FloatingDecimal$BinaryToASCIIBuffer.appendTo(FloatingDecimal.java:307) 
at sun.misc.FloatingDecimal.appendTo(FloatingDecimal.java:89) 
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:709) 
at java.lang.StringBuilder.append(StringBuilder.java:226) 
at edu.modesta.test.octree.Octree.add_nodes(Octree.java:73) 
at edu.modesta.test.octree.Octree.add_nodes(Octree.java:97) 
at edu.modesta.test.octree.Octree.add_nodes(Octree.java:107) 
at edu.modesta.test.octree.Octree.add_nodes(Octree.java:107) 
at edu.modesta.test.octree.Octree.add_nodes(Octree.java:107) 

和一個額外的400線中的edu.modesta.test.octree.Octree.add_nodes(Octree.java:107)錯誤

希望有人能回答。謝謝!

回答

1

我不是100%確定的,因爲我看不到剩餘的代碼,但它看起來像在i >= 8時輸入add_nodes()。從此,你的控制流說

if (this.childNodes == null),然後做一些東西叫add_nodes()

else if (childNodes != null),做一些東西,然後調用add_nodes()

無論哪種方式,你打電話add_nodes()如果i不小於8,因爲你永遠不會遞減i,每個後續調用會調用add_nodes()了。

每次調用方法時,新方法的框架都會被添加到堆棧上。當最終該堆棧變得太大時發生StackOverflowException。既然你假設無限次地調用add_nodes(),每次調用都會增加一點,直到變得太大,因此你的異常。

另一方面:我有點困惑,你爲什麼提到childNodesthis.childNodes,也只是childNodesthis通常只有當您有兩個變量的範圍不同但名稱相同時才需要,您不在此處。你也許想要刷上using this