Java: trouble understanding recursive method calling

geekTechnique :

I hope you're all having a good day.

My teacher has confused the pants off me. I've read my book and researched, but I'm still confused. I'm just now learning methods, so I have a long way to go. I made an 'Oregon Trail' like game, it uses a 'game over' method to ask if the user wants to play again.

The main issue: My teacher mentioned something vague about if the game looped enough times, we'd end up with a stackOverflow. That makes sense to me, because the game continues to nest methods inside of each other the way I have it, adding to the stack each time a 'new game' method is called, because the outer methods are still there waiting to complete.

I've boiled down an example of what I mean. Assuming there were pauses for user input and such, how am I supposed to make sure my memory utilization doesn't keep growing as I call methods inside other methods? I think the word for this is 'recursive', thus my title.

Please, if anyone could recommend good form for dealing with this, I'd be really grateful.

public class Testing
{
    public static void main(String[] args) {
        System.out.println("main method");
        gameStart();
    }

    private static void gameStart()
    {
        System.out.println("some other method called");
        gameOver();
    }

    private static void gameOver()
    {
        System.out.println("game over called"); //I would ask the user if they want to play again.
        //keeping it concise to illustrate my point, instead of using an if statement
        gameStart();//starting the cycle I'm concerned about. Assume the user indicated they would like to play again.
    }
}
Hero Wanders :

To avoid unlimited recursion you may switch over to iteration and introduce return values for those methods which currently decide how to proceed (currently by directly calling the corresponding actions). Let those methods return some sign what to do next, for example by using an enum. Then write a loop which calls the right methods depending on the return values.

Example (abbreviated, I assume you know Java syntax):

enum Action { Start, ShowEnd, Quit }

main:

Action nextAction = Action.Start;
while (action != Action.Quit)
{
    switch (action)
    {
        case Start:
            nextAction = gameStart();
            break;
        case ShowEnd:
            nextAction = gameEnd();
            break;
        // ToDo: write more actions!
        default:
            break;
    }
}

This assumes that each such method executes until a decision was made about which action to take next.

This way your call stack will always be quite flat, as the execution always returns to the main method and then branches off into other methods.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91293&siteId=1