Noam Hudson
Noam Hudson

Reputation: 151

Why is this boolean coming out false even when one of the conditions is true?

So I have this simple boolean method for checking whether my game has ended. In the main method, I then have a big loop that starts with the statement while (isGameEnd() == false) {...}. This loop never seems to break, even when one, two or all of the conditions in the method becomes true. I don't get it.

public static boolean isGameEnd() {
        if (lives == 0 || steps == 0 || isMazeCompleted()) { return true; }
        else { return false; }
}

Upvotes: 1

Views: 839

Answers (1)

gringer
gringer

Reputation: 420

The use of static in the function definition is a red flag to me. If a class is defined with default field values, then those default values will be what is checked rather than the particular implementation of the class:

class Game {
  int lives = 3;
  int steps = 10;
  public boolean isMazeCompleted() {
    return false;
  }
  public void doStuff() {
    lives--;
  }
  public static boolean isGameEnd() {
    if (lives == 0 || steps == 0 || isMazeCompleted()) {
      return true; 
    } else { 
      return false; 
    }
  }
}

public static void main(String[] args){
  Game a;
  while(!a.isGameEnd()){ // check 'isGameEnd' for the static class
     a.doStuff(); // This does *not* update the static class
  }
}

Most Java editors will complain about the use of static functions in a non-static context, so will suggest Game.isGameEnd() instead of a.isGameEnd(), which makes it a bit more obvious to the programmer where the error is.

Upvotes: 1

Related Questions