On the previous page we looked at while loops. Here are some more examples of various ways that they can be used.
Three ways to write while loops (four, including do-while):
| 1. using while(true) and break; |
|---|
while (true) {
int r = (int)(Math.random()*20) + 1;
System.out.print(r + " ");
if (r == 13) break;
}
System.out.println("loop 1 finished");
|
| 2. using a condition in the while statement |
int r=-1; //create and initialize variable.
//Make sure the variable has a value that ensures that the loop executes at least once
while (r != 13) {
r = (int)(Math.random()*20) + 1;
System.out.print(r + " ");
}
System.out.println("loop 2 finished");
|
| 3. use a boolean (flag, sentinel) |
boolean keepLooping = true;
while( keepLooping) {
r = (int)(Math.random()*20) + 1;
System.out.print(r + " ");
if (r == 13) keepLooping = false;
}
System.out.println("loop 3 finished");
//you should be able to do this with a false value as well
|
| 4. Do While construct |
|---|
do {
r = (int)(Math.random()*20) + 1;
System.out.print(r + " ");
} while ( r != 13);
System.out.println("loop 4 finished");
|
Teaching points:
if (gameOn) rather than if (gameOn == true) if (!gameOn) rather than if (gameOn == false)
This avoids the very subtle error of mistakenly typing if (gameOn = true)
LOOPS: http://www.cs.uah.edu/~rcoleman/CS121/ClassTopics/Loops.html
Conditional statements: http://www.cs.uah.edu/~rcoleman/CS121/ClassTopics/Conditionals.html