Skywarp
Skywarp

Reputation: 1059

Java Method is skipping return statement

This java method is skipping over a return statement. I was wondering if anybody has encountered this and know of a solution. Whatever the bug is it's very subtle.

public GameState getNextGameState() {
    if (player.getLives() > 0) {
        if (!player.isAlive()) {
            System.out.println("checkpoint 1");
            player.setIsAlive(true);
            return new PlayField(width, height, hiScores, player.setCoordinates(width / 2, height - 8),
                    stagePattern, stage);
        }
        System.out.println("checkpoint 2");
        if(++stage > 29)
            stage = 0;

        return new PlayField(width, height, hiScores, player.setCoordinates(width / 2, height - 8), stage);
    }
    return new GameOver(Game.key, hiScores, player.getRank());
}

Here is a screenshot with console output to prove it: enter image description here

Also, this bug only started happening when I put my gamestates in a stack structure. Here is the code I'm now using for the gamestate transition:

public void update() {

    gsm.peek().update();

    if(gsm.peek().finished)
        if(gsm.peek().getNextGameState() == null)
            gsm.pop();
        else
            gsm.push(gsm.pop().getNextGameState());             
}

gsm declaration is:

public static Stack<GameState> gsm = new Stack<GameState>();

Hopefully someone has some insight. Thank you!

Upvotes: 1

Views: 1147

Answers (2)

jlonghi
jlonghi

Reputation: 21

Can you post more code? You are probably calling it twice and it is not skipping over the return. If you really think it is put a break point to assist you with debugging and watch the code run.

Upvotes: 1

davidxxx
davidxxx

Reputation: 131356

It is not the result of the same call.
You call twice the method here.
The first time it is not alive, the second is alive. So you have the both message in the output.
In a game, the update phase is called in a continuous way.
Just add a System.out.println at the beginning of the method (that is before the conditions) and you could have the confirmation :

public GameState getNextGameState() {

     System.out.println("enter method");
     ...
}

Upvotes: 1

Related Questions