2015-01-16 40 views
0

所以我試圖繪製一棵樹,使用遞歸和一個小程序。我的分支生成的很好,但方法的第二次調用從未被調用。我尋找其他解決方案,但我似乎無法找到任何類似於我的問題。如果我註釋掉第一個分支()的調用,那麼第二個分支就會工作,並且問題會顛倒過來。謝謝你的幫助。Java:遞歸|將遞歸樹繪製爲圖形|不會調用第二個方法

public class Tree extends Applet{ 

int x,y,x1,x2,y1,y2; 
int width,height; 
int len,temp1 = 0,temp2 = 0; 

double bran,count; 
int ang; 
double rand; 

Image page; 
Graphics draw; 

public void init(){ 
    width = 1000; 
    height = 600; 
    setSize(width,height); 
    setBackground(Color.black); 

    count = 21; 
    bran = 50; 
    //ang = 10; 

    page = createImage(width,height); 
    draw = page.getGraphics(); 

    x = width/2; 
    y = height; 

    x1=x; 
    y1=y; 

    x2=x1; 
    y2=y1-100; 

} 

public void paint(Graphics g){ 
    draw.setColor(Color.green); 
    branch(draw,x2,y2,20); 
    g.drawImage(page,0,0,width,height,this); 


} 

public void branch(Graphics g,int x,int y,int ang){ 
    count-=1; 

    if(count%2 == 0) 
     bran-=2; 

    if(count == 20){ 
     g.drawLine(x1,y1,x2,y2); 
    } 
    else if(count > 0){ 
     x1 = x; 
     y1 = y; 

     rand = ang * (Math.PI/180); 

     int xChange = (int) (Math.sin(rand)*bran); 
     int yChange = (int) (Math.cos(rand)*bran); 
     y2 = y-yChange; 

     /*System.out.printf("X1 | %3d \t X2 | %3d \t Y | %3d \t ChangeX | %3d \t ChangeY | %3d \n", 
       x1-xChange,x1+xChange,y2,xChange,yChange);*/ 


     g.setColor(Color.blue); 
     g.drawLine(x1,y1,x1-xChange,y2); 
     g.setColor(Color.orange); 
     g.drawLine(x1,y1,x1+xChange,y2);    

     branch(g,x1-xChange,y2,ang+10); 

     temp1++; 
     System.out.print("End1 | "+temp1); 

     branch(g,x1+xChange,y2,ang+10); 

     temp2++; 
     System.out.println("\tEND2 | "+temp2); 
    } 
}//End of branch 

}

回答

0

當到達第二個電話,count <= 0是真實的,因爲count是永遠不會遞增一個全局變量。

爲了解決這個問題,變動計數是該方法的參數:

public void branch(Graphics g, int x, int y, int ang, int count) { 
    // ... 
    branch(g, x1-xChange, y2, ang+10, count - 1); 
    // ... 
    branch(g, x1+xChange, y2, ang+10, count - 1); 
    // ... 
} 

,並在paint方法初始呼叫:branch(draw, x2, y2, 20, 21);

+0

所以我所做的更改,不得不改變** if(count == 20){g.drawLine(x1,y1,x2,y2); } **,因爲它會通過,沒有別的東西可以顯示。它仍然不顯示/經歷所有的遞歸調用。我不知道它是否需要時間緩衝,但它只在**分支的第10次調用(g,x1 - xChange,y2,ang + 10,count - 1)上繪製新分支** – Dontstealthisname

+0

您能編輯問題中的代碼反映了這一點? – user1207177

+0

對不起,我修好了一些擺弄之後。我將x1-xChange和x1 + xChange定義爲xEnd1和xEnd2,它現在可以工作。 – Dontstealthisname