Execute while the loops are running only if there is an instruction in it?

Probably a very simple answer to this question, but I just don't get it because I recently learned Java. Take this simple code for example:

public class Test4 extends JFrame implements KeyListener {
public Test4(){
    super("Test");
    setSize(10,10);
    addKeyListener(this);
    setVisible(true);
}
static boolean test = true;
public static void main(String[] args){
    Test4 frame = new Test4();

    while(test){
        //When I put a System.out.println statement here it will print Testing or some other statement otherwise it will not print Testing.
    }
    System.out.println("Testing");
}

public void keyPressed(KeyEvent arg0) {
    int pressed = arg0.getKeyCode();

    if(pressed == 87){//w key
        test = false;
    }
}

      

Here is the problem I ran into, with no statement in the while loop, it won't print Testing when test = false, but with the statement, it will go through the while loop and wait for test = false and then print Testing. Basically what this test program is trying to do is wait until you press the w key and then it will print Testing, but the while loop will wait for a key press if there is an expression in it ... I hope I had some meaning. I know there are many other more efficient ways to make the program wait until the key is updated, but this is just a test to see if the while loop works without any instructions, and it does not currently work. if there are no statements I just want to know why. Thank.

+3


source to share





All Articles