Sunday, August 15, 2010

6. The while loop

Okay now that you've learned about the for loop you can learn about the while loop!!!!!

The while loop doesn't have all that complicated stuff in the parentheses you just have to put something that is true or false and it will execute it while it is true!  This leads right into a new variable, the boolean!!!!.

To create a boolean you just do:
boolean a = true;
boolean b = 1 < 2;

So both of these statements would be true because we set a to true and we set b to 1 is less than 2 which is also true.  The boolean is nice for while loops because the while loop will keep going until you set a boolean to false. (I'll get to this in just a sec)

So here's how you set up a while loop.

while(1<2) {
   System.out.println("1");


You say while(something is true) do it.  This loop would print out 1 infinitely so it's probably not a good idea to do it right now.  Now here's a way to use booleans in while loops. 

boolean c = true;
while(c) {
   System.out.println("c is true");
   c = false;
} 

This while loop would check if c is true.  Print out "c is true" and then set c to false.  So it should only print out "c is true" once.

The while loop is a good way to keep the computer processing something.  It is used in games to keep redrawing the screen.  Right now the for loop is probably the better loop for a beginner but it is good to have the knowledge of a while loop.

If you are confused just drop a comment!