4

我正在学习用 Java 编写代码,并且已经了解了 Java 编程的递归部分。我了解递归方法的基础知识,并且正在尝试编写填充希尔伯特曲线(和 Levy C 曲线)的空间,到目前为止,在实际递归部分之前,一切都很顺利。我在想出递归方法时遇到了麻烦,想知道是否有人可以帮助我。我也知道它需要在 DrawHilbert 方法中。

public class HilbertCurve extends JPanel {
int N;

/**
 * Constructor for Hilbert Curve
 */
public HilbertCurve () 
{
    Scanner myKeyboard = new Scanner(System.in);
    System.out.println("Enter an integer number to indicate the level of recursive depth: ");
    N = myKeyboard.nextInt();
    // Create a JFrame - a window that will appear on your screen
    JFrame f = new JFrame();

    // Tells the program to quit if you close the window
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Puts your drawing into the window (the JFrame)
    f.add(new JScrollPane(this));
    // Changes the size of the window on the screen
    f.setSize(600, 600);
    // Changes where the window will appear on your screen
    f.setLocation(200, 200);
    // Makes the window appear
    f.setVisible(true);
}
public void setupHilbert (Turtle turtle) 
{
    turtle.penup();
    turtle.setXY(0,0);

    // draw a simple rectangle that is 100x50 pixels
    turtle.pendown();

    drawHilbert(turtle, N); 
}

public void drawHilbert(Turtle turtle, int n) {

    if (n == 0) return;
    turtle.changeColor(Color.GREEN);
    turtle.changeWidth(2);
    turtle.left(-90);
    turtle.forward(100);
    turtle.left(90);
    turtle.forward(100);
    turtle.left(90);
    turtle.forward(100);
    turtle.left(-90);
    turtle.penup();
}

protected void paintComponent(Graphics g)
{
    Turtle turtle = new Turtle((Graphics2D) g, getBounds());

    turtle.setHeadingMode(Turtle.DEGREE);
    setupHilbert(turtle);

}


// plot a Hilbert curve of order N
public static void main(String[] args) 
{
    Scanner myKeyboard = new Scanner(System.in);
    HilbertCurve test = new HilbertCurve();
}

}

4

1 回答 1

1

递归的标志是一个函数调用自身。我希望drawHilbert()在某个地方看到对内部自身的调用,但我没有。

请密切注意您的停止条件,否则您最终会遇到 OutOfMemoryError,因为您的递归调用将永远添加到堆栈中。

我不熟悉您的问题,但这会是您所缺少的吗?

public void drawHilbert(Turtle turtle, int n) {

    if (n == 0) return;
    turtle.changeColor(Color.GREEN);
    turtle.changeWidth(2);
    turtle.left(-90);
    turtle.forward(100);
    turtle.left(90);
    turtle.forward(100);
    turtle.left(90);
    turtle.forward(100);
    turtle.left(-90);
    turtle.penup();
    drawHilbert(turtle, --n);  // is this where your recursion should go?
}

更新:这个网站看起来很相关。

http://people.cs.aau.dk/~normark/prog3-03/html/notes/fu-intr-2_themes-hilbert-sec.html

于 2012-05-04T12:30:36.967 回答