Search code examples
javaswingnetbeanswhile-loop

Issue with a while-loop while executing it


I have a program that implements a minigame with swing, and in the main class I have a loop which listens to a Boolean in the map of the game. The loop implemented with while does not execute an instruction if it is the only one and I don`t know why.

I tried putting some other instructions to check if loop goes on, and it worked fine, but when I put only the if that I want it does not work.

public class ejecutor extends JFrame{
boolean ejecutando = true;
    
    public ejecutor(){
        mapa mapa = new mapa(); //the map of my game
        setSize(665,690);
        add(mapa);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
        while(ejecutando){ 
            if(mapa.todasComidas()){
            //wLabel();
            ejecutando=false;
            System.out.println("You finished!!");
            }
//If I put this println it works, if I only use the If, without any other instruction inside the while, it does not do anything at all
            System.out.println("............");
        }
    }
//I execute the constructor in the main...

Solution

  • By default boolean variables of a Java Object in Java gets set to default value as false. Looking at your code mapa.todasComidas(), you never explicitly set the same.

    Now in your while loop, you are checking whether todasComidas method returns you true which won't be the case and hence never resets the same i.e. execute the inner statements of if condition. Your outer statement does gets executed and prints on console as its not guarded by any if conditions.