Recursively dividing up square regions

I'm trying to divide square into 4 smaller quadrants by randomly selecting a point in the square and drawing two lines through it, and then dividing each of those quadrants up into 4, and so on, until the width/height is 1, in a recursive way. My code is here:

public static void draw(int x0, int y0, int xmax, int ymax) {

if (Math.abs(xmax - x0) > 1 && Math.abs(ymax - y0) > 1) {
    int rx = r.nextInt(xmax - 1) + 1;    // line A
    int ry = r.nextInt(ymax - 1) + 1;    // line B

    StdDraw.line(rx, y0, rx, ymax);
    StdDraw.line(x0, ry, xmax, ry);

    draw(x0, y0, rx, ry);        // line C
    draw(x0, ry, rx, ymax);      // line D
    draw(rx, ry, xmax, ymax);    // line E
    draw(rx, y0, xmax, ry);      // line F
}
else ;

That is, I'm passing the lower left corner coordinates (x0, y0) and the upper right corner coordinates (xmax, ymax). Whenever I comment out lines D, E, and F, everything works fine. But when I uncomment any of D, E, or F, I get this error java.lang.IllegalArgumentException: n must be positive , usually pointed at line A or line B. Can someone please tell me what this error means and how I can fix it?


Considering that nextInt(int n) seems to contain the only n variable in that piece of code it is likely the one that is throwing that error.

Make sure that xmax-1 and ymax-1 don't become negative as the documentation for nextInt specifically says it throws this error on negative numbers:

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt(int)


This is because somewhere during your recursion the value passed in nextInt -> (xmax - 1) is becoming negative.

r.nextInt(xmax - 1);

If (xmax - 1) is negative you will get exception. Because, nextInt() method takes only positive values.

  • You can add an additional check before this line to check whether your difference is negative or positive. And accordingly, you can skip this part of code.
  • 链接地址: http://www.djcxy.com/p/80700.html

    上一篇: 使用java的递归方法绘制正方形

    下一篇: 递归地划分正方形区域