Help for while loop

edited March 2018 in How To...

I am trying to add a while loop to my code .

Something like while ENTER is pressed println "you are pressing enter" .

Can someone please help me ?

Is this code goes into the void draw() ?

What would the code be for that ?

Answers

  • See the reference for while

    and for keyPressed and key

    It won’t work in my opinion. Draw() updates keyPressed only at the end of draw and not during while. iirc

    But try

    int i=0;

    while (i<10) {

    println(i);

    i++;

    }

    println („done“); use normal „“ here

  • Answer ✓

    You should not use a while loop. You should use a boolean and an if statement.

    boolean enterPressed;
    
    void setup(){
      size(200,200);
    }
    
    void draw(){
      background(0);
      if( enterPressed ){
        text("ENTER", 100, 100);
      }
    }
    
    void keyPressed(){
      if( keyCode == ENTER ){
        enterPressed = true;
      }
    }
    
    void keyReleased(){
      if( keyCode == ENTER ){
        enterPressed = false;
      }
    }
    
  • To explain more why the first approach won't work:

    1. The keypressed variable is updated at the end of the draw loop.
    2. If you check it during the draw loop, it will either be true or false -- and that won't change.
    3. If it is true, your while loop will go on forever -- letting go of the key won't change anything, as it won't be update until the end of draw, and it will never exit the while loop to get to the end of draw.
Sign In or Register to comment.