开发者

Recursive method in Java seems to just "goto" the first line of the method instead of actually go into the next call

I am creating a factory that make开发者_开发技巧s rooms, and it is passed an int of steps and a start room and it is supposed to do a step, build a room, and then call itself with one fewer step and the new room as the start room. The problem is that it never ends. In the debugger, I can see that it's calling itself, which creates another method call in memory that actually has one fewer step, but then the execution line goes to the top of the current method call! so it never actually completes the new call. As though it were putting the new call into heap instead of stack, and then never actually getting to it.

Code:

@Override
public Room place(Level level, int cycles, Room start_room,
        Direction direction, int shop, int exit, LevelFactoryReport report) throws Exception
{


    Room room = null;
    if(cycles < 1)
    {
        return start_room;
    }
    else
    {
        report.addEvent("--Placer step--");
        report.addEvent("Steps remaining: "+cycles);
        room = this.Step(level, start_room, direction, shop, exit, report);
        if(room == null)
        {
            cycles = 0;
            report.addEvent("Step returned a null room (probably because it ran into an existing room). Ending cycle.");
        }
    }
    return place(level, (cycles--), room, direction, (shop--), (exit--), report);
}

In the code above, it goes through the various implementation, then gets to the new call for place(), and then it just creates a new instance of place(), but doesn't step into it, and instead the execution line goes back to "Room room = start_room" of the original call. It does this infinitely, with the cycles always at its initial value of 4, and more and more instances of place() filling up the stack. I looked into the new instances, and all of them actually do have a "cycles" value of 3.

The strange thing is, each iteration that actually runs is being run on the next room, so when it goes back to the top, it is going back to the top passing the next room. But why is it creating a new instance of place() (with the new room AND the new cycles value of 3), and then re-running the old place() using the new room BUT NOT the new cycles value of 3?


You're using cycles--, shop-- to decrement the variables. However while x-- does decrement x, it does not return the decremented value. The return value of the expression x-- is the old value of x. Use x-1 instead of x--. (Or --x if you must, but there is no point in mutating the variable here).


try replacing this line:

return place(level, (cycles--), room, direction, (shop--), (exit--), report);

with this line:

return place(level, (--cycles), room, direction, (--shop), (--exit), report);

Maybe you can find some more help here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜