簡體   English   中英

Java:遞歸 繪制遞歸樹作為圖形 不會調用第二種方法

[英]Java : Recursion | Drawing a recursive tree as a graphic | Won't call second method

因此,我試圖使用遞歸和小程序繪制一棵樹。 我的分支生成正常,但是從未調用過該方法的第二次調用。 我在尋找其他解決方案,但似乎找不到與我的問題類似的東西。 如果我注釋掉branch()的第一個調用,則第二個工作正常,問題就解決了。 謝謝你的幫助。

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

}

當第二個呼叫到達時, count <= 0為true,因為count是一個永遠不會增加的全局變量。

要解決此問題,請將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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM