Java Reference
In-Depth Information
This statement defines and initializes a counter but we have not defined a counter update. Because the counter
is never updated, the condition will always be true and the println statement will execute endlessly. What we have
created is called an endless (or infinite ) loop . Do I need to tell you that this is a bad thing?
If you were to run the application now, it would run until you either terminated it from the Console view or
closed RAD.
We definitely need to update the ctr so that it reaches 10 and the loop is ended.
6.
After the println statement, add the following:
ctr = ctr + 1;
7.
Save and run LoopTestApp.
The results will be the same as the for loop: 10 lines with the counter (ctr) value followed by the word “little.”
8.
Comment out the while loop (don't comment out the ctr definition).
9.
Add the following do while loop after the ctr definition:
do {
System.out.println(ctr + " little");
ctr = ctr + 1;
} while (ctr <= 10);
10.
Save and run LoopTestApp.
Once again, the same results will be displayed. You may be wondering why there are three methods for defining
loops. Unfortunately, you do not have enough programming experience to appreciate the subtle differences between
the three methods. When we change our application to access a database, your appreciation of loops will grow
considerably.
Tutorial: More About Iteration
The keywords break and continue are often used with loops. A break statement ends the loop. This means that the
first statement following the loop will be executed. A continue statement bypasses any remaining statements within
the loop but does not end the loop. A continue statement in a for loop results in the counter being updated, and the
next iteration is performed. In while and do while loops, a continue forces the JVM to perform the condition test and
either perform another iteration or end the loop.
Both keywords are usually used within an if statement to stop looping or to skip the remaining statements in one
iteration of a loop. Let's try to skip the “5 little” text.
1.
In LoopTestApp, comment out the do while loop (don't comment out the ctr definition).
2.
Add the following do while loop and run the application:
do {
System.out.println(ctr + " little");
if (ctr == 5) {
break ;
}
ctr = ctr + 1;
} while (ctr <= 10);
 
Search WWH ::




Custom Search