2017-02-16 34 views
1

我正在嘗試在Processing/Java中編寫名爲Branch的類。我已經通過全局變量給它一個轉義條件,但它創建了太多的遞歸和一個計算器。我很難理解爲什麼。即使退出條件,euclidean樹對象堆棧溢出錯誤

int maxIterations = 10; 
int iterations = 0; 

class Branch 
{ 
    //props 
    float angle, scale, drawingScale; 
PVector origin, destination; 
//konstrukt 
Branch (float _x, float _y, float _angle, float _scale) { 
    origin = new PVector(_x,_y); 
    angle = _angle; 
    scale = _scale; 
    calculateDestination(); 
    drawMyself(); 
    rebirth(); 
    } 

    void rebirth() { 
    if(iterations < maxIterations) { 
     Branch bLeft = new Branch(destination.x,destination.y,angle-50,100); 
     Branch bRight = new Branch(destination.x,destination.y,angle+50,100); 
     iterations++; 
    } 
    } 

    void calculateDestination() { 
    //se till att skala alltid går uppåt. 
    scale = abs(scale); 
    scale = -scale; 
    destination = new PVector(origin.x+angle,origin.y+scale); 
    } 

    void drawMyself() { 
    drawingScale = scale * -1; 
    strokeWeight(10); 
    beginShape(LINES); 
    vertex(origin.x,origin.y); 
    vertex(destination.x, destination.y); 
    endShape(); 

    ellipseMode(CENTER); 
    fill(255); 
    ellipse(origin.x,origin.y,scale/3,scale/3); 
    ellipse(destination.x,destination.y,scale/3,scale/3); 

    } 


}//End Branch; 

任何幫助理解爲什麼溢出或如何有效地在對象內使用遞歸非常appareiciated!

+0

如果可能,最好有更多關於您遇到的錯誤的信息,例如,回溯。 –

回答

1

創建兩個新分支後,您增加迭代的唯一位置是rebirth()。問題是這個增量從未達到。

你有什麼是rebirth()電話Branch()這就要求rebirth()這就要求Branch()等,並且永遠不會執行iterations++

在致電Branch之前,您應該增加iterations。此外,將其用作參數而不是全局變量

+0

謝謝!在創建一個新的分支之前放置迭代,可以避免溢出。我現在看到我還有另一個問題需要解決,我希望能夠創建兩個新的分支,一個分支具有負面角度,另一個分支具有積極的分支會使他們始終分裂成兩個分支。然而,這是運行代碼的結果: http://imgur.com/a/t1oYN 我用這些參數在程序中啓動對象:'b1 = new Branch(width/2,height,0,100 );' – MidwinterAlphawave

+0

我在上面的評論中解決了這個問題,爲迭代創建了一個參數。 謝謝你非常有幫助的回答:) – MidwinterAlphawave