简体   繁体   中英

Recursively Drawing Circles

I am trying to draw this: 在此输入图像描述

public void drawCircle(int x, int y, int diameter, int it) {
    int d = diameter / 3;
    if (it == 0) {
        return;
    }
    g.setColor(Color.green);
    g.fillOval(x, y, d, d);
    drawCircle(x, y, d, it--); // centre
    drawCircle(x - d, y, d, it--); // left
    drawCircle(x + d, y, d, it--); // right

}

For the purposes of this question, ignore the actual positions of the where I draw the circles - I will change this later as it's not quite right. However, where am I going wrong within the logic of my program? For me, it seems clear I am calling the method to draw three circles every iteration. Here is my error:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.java2d.loops.ProcessPath.ProcessMonotonicCubic(Unknown Source)
at sun.java2d.loops.ProcessPath.ProcessCubic(Unknown Source)
at sun.java2d.loops.ProcessPath.doProcessPath(Unknown Source)
at sun.java2d.loops.ProcessPath.fillPath(Unknown Source)
at sun.java2d.pipe.BufferedRenderPipe.fillPath(Unknown Source)
at sun.java2d.pipe.BufferedRenderPipe.fill(Unknown Source)
at sun.java2d.pipe.BufferedRenderPipe.fillOval(Unknown Source)
at sun.java2d.SunGraphics2D.fillOval(Unknown Source)
at Draw.drawCircle(Draw.java:40)
at Draw.drawCircle(Draw.java:41)

Here are lines 40 and 41:

g.fillOval(x, y, d, d);
drawCircle(x, y, d, it--); // centre

Thanks for help.

Your recursive call receives the same value of it during each recursive call, because it-- returns the value of it before it decrements.

Assuming you want to keep the value of it intact throughout one iteration, just pass it - 1 to the recursive call, eg

drawCircle(x, y, d, it - 1); // centre

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM