Hour 8. Repeating An Action With Loops
Hour 8. Repeating An Action With Loops
One of the more annoying punishments for schoolchildren is to make them write something over and
over again on paper or a chalkboard.
On The Simpsons, in one of his frequent trips to the board, Bart Simpson had to write, "I am not
certified to remove asbestos" dozens of times. This kind of punishment might work on children, but it
definitely would fail to be punitive to a computer, which can repeat a task with ease.
Computer programs are ideally suited to do the same thing over and over again because of loops. A
loop is a statement or set of statements that will be repeated in a program. Some loops take place a
fixed number of times. Others take place indefinitely.
There are three loop statements in Java: for, do, and while. These statements are often interchangeable
in a program because each can be made to work like the others. The choice to use a loop statement in
a program often depends on personal preference, but it's beneficial to learn how all three work. You
can frequently simplify a loop section of a program by choosing the right statement.
Naming a loop
for Loops
In the Java programs that you write, you will find many circumstances in which a loop is useful. You
can use them to keep doing something several times, such as an antivirus program that opens each
new email you receive to look for any viruses. You also can use them to cause the computer to do
nothing for a brief period, such as an animated clock that displays the current time once per minute.
To create and control loops, you use a loop statement. A loop statement causes a computer program to
return to the same place more than once. If the term seems unusual to you, think of what a stunt plane
does when it loops: It completes a circle and returns to the place where it started the loop.
The most complex of the loop statements is for. The for loop is often used in cases where you want to
repeat a section of a program for a fixed amount of times. It also can be used if the number of times
the loop should be repeated is based on the value of a variable. The following is an example of a for
loop:
This loop displays every number from 0 to 999 that is evenly divisible by 12.
Every for loop has a variable that is used to determine when the loop should begin and end. This
variable often is called the counter. The counter in the preceding loop is a variable called dex.
The initialization section: In the first part, the dex variable is given an initial value of 0.
The conditional section: In the second part, there is a conditional test like one you might use
in an if statement. The test is dex < 1000.
The change section: The third part is a statement that changes the value of the dex variable by
using the increment operator.
In the initialization section, you can set up the counter variable you want to use in the for statement.
You can even create the variable inside the for statement, as the preceding example does with the
integer variable named dex. You can also create the variable elsewhere in the program. In any case,
the variable should be given a starting value in this section of the for statement. The variable will have
this value when the loop starts.
The conditional section contains a test that must remain true for the loop to continue looping. Once
the test is false, the loop will end. In this example, the loop will end when the dex variable is equal to
or greater than 1,000.
The last section of the for statement contains a Java statement that changes the value of the counter
variable in some way. This statement is handled each time the loop goes around. The counter variable
has to change in some way or the loop will never end. For instance, in this example, dex is
incremented by one using the increment operator ++ in the change section. If dex was not changed, it
would stay at its original value, 0, and the conditional dex < 1000 would always be true.
The statements inside the bracket marks, { and }, are also executed during each trip through the loop.
The bracketed area is usually where the main work of the loop takes place, although some loops do all
their work in the change section.
The preceding example had the following statement within the { and } marks:
This statement will be executed 1,000 times. The loop starts by setting the dex variable equal to 0. It
then adds 1 to dex during each pass through the loop and stops looping when dex is no longer less
than 1,000. Every time dex is evenly divisible by 12, the number is displayed next to the text #:.
Note
An unusual term you might hear in connection with loops is iteration. An iteration is a single trip
through a loop. The counter variable that is used to control the loop is often called an iterator.
As you have seen with if statements, a for loop does not require brackets if it contains only a single
statement. This is shown in the following example:
This loop will display the text "I am not certified to remove asbestos" 500 times. Although brackets
are not required around a single statement inside a loop, you can use them if desired as a way of
making the program easier to understand.
The first program you create during this hour will display the first 200 multiples of 9: 9 x 1, 9 x 2, 9 x
3, and so on, up to 9 x 200. Because this task is so repetitious, it should be handled with a loop
statement such as for.
Open your word processor and create a new file. Enter the text of Listing 8.1 and save the file as
Nines.java when you're done.
1: class Nines {
2: public static void main(String[] arguments) {
3: for (int dex = 1; dex <= 200; dex++) {
4: int multiple = 9 * dex;
5: System.out.print(multiple + " ");
6: }
7: }
8: }
The Nines program contains a for statement in Line 3. This statement has three parts:
The initialization section: int dex = 1, which creates an integer variable called dex and gives it
an initial value of 1.
The conditional section: dex <= 200, which must be true during each trip through the loop.
When it is not true, the loop ends.
The change section: dex++, which increments the dex variable by one during each trip
through the loop.
Compile and run the program. If you are using the SDK, you can handle these tasks by using the
following commands:
javac Nines.java
java Nines
The for loop statement is extremely useful. You'll get a lot of practice using it in upcoming hours,
because several of the tutorial programs and workshops make use of these loops.
Note
Because many Java statements end with a semicolon, an easy mistake to make is putting a semicolon
at the end of a for statement, as in the following:
Look closely at the closing parenthesis in this example. It is followed by a semicolon, which will
prevent the loop from running correctly. The semicolon puts the statements in the brackets, value =
value + i;, outside the loop. As a result, nothing will happen as the for loop is handled. The program
will compile without any errors, but you won't get the results you expect when it runs.
while Loops
The while loop does not have as many different sections to set up as the for loop. The only thing it
needs is a conditional test, which accompanies the while statement. The following is an example of a
while loop:
This loop will continue repeating until the game Lives variable is no longer greater than 0.
The while statement tests the condition at the beginning of the loop, before any statements in the loop
have been handled. For this reason, if the tested condition is false when a program reaches the while
statement for the first time, the statements inside the loop will be ignored.
If the while condition is true, the loop goes around once and tests the while condition again. If the
tested condition never changes inside the loop, the loop will keep looping indefinitely.
The following statements cause a while loop to display the same line of text several times:
int limit = 5;
int count = 1;
while (count < limit) {
System.out.println("Frodo lives!");
count++;
}
A while loop uses one or more variables that are set up before the loop statement. In this example, two
integer variables are created: limit, which has a value of 5, and count, which has a value of 1.
The while loop displays the text Frodo lives! four times. If you gave the count variable an initial value
of 6 instead of 1, the text would never be displayed.
do-while Loops
The do-while loop is similar in function to the while loop, but the conditional test goes in a different
place. The following is an example of a do-while loop:
do {
// the statements inside the loop go here
} while ( gameLives > 0 );
Like the previous while loop, this loop will continue looping until the gameLives variable is no longer
greater than 0. The do-while loop is different because the conditional test is conducted after the
statements inside the loop, instead of before them.
When the do loop is reached for the first time as a program runs, the statements between the do and
the while are handled automatically. Then the while condition is tested to determine whether the loop
should be repeated. If the while condition is true, the loop goes around one more time. If the condition
is false, the loop ends. Something must happen inside the do and while statements that changes the
condition tested with while, or the loop will continue indefinitely. The statements inside a do-while
loop will always be handled at least once.
The following statements cause a do-while loop to display the same line of text several times:
int limit = 5;
int count = 1;
do {
System.out.println("Frodo lives!");
count++;
while (count < limit)
Like a while loop, a do-while loop uses one or more variables that are set up before the loop
statement.
The loop displays the text Frodo lives! four times. If you gave the count variable an initial value of 6
instead of 1, the text would be displayed once, even though count is never less than limit.
If you're still confused about the difference between a while loop and a do-while loop, engage in a
little role-playing and pretend you're a teenager who wants to borrow your father's car. If you are a
teenager, all the better. There are two strategies that you can take:
1. Borrow the car first and tell Dad later that you did it.
Strategy 1 has an advantage over Strategy 2: even if Dad doesn't want to let you use the car, you get to
borrow it once.
The do-while loop is like Strategy 1 because something happens once even if the loop condition is
false the first time while is encountered.
The while loop is like Strategy 2 because nothing will happen unless the while condition at the
beginning is true. It all depends on the situation in your program.
Note
Sams Publishing makes no warranties express nor implied that your father will be happy if you
borrow his car without telling him first.
Exiting a Loop
The normal way to exit a loop is for the condition that is tested to become false. This is true of all
three types of loops in Java: for, while, and do-while. However, there might be times when you want a
loop to end immediately, even if the condition being tested is still true. You can do this with a break
statement, as shown in the following code:
int index = 0;
while (index <= 1000) {
index = index + 5;
if (index == 400)
break;
System.out.println("The index is " + index);
}
The condition tested in the while loop sets it up to loop until the value of the index variable is greater
than 1,000. However, a special case causes the loop to end earlier than that: If index equals 400, the
break statement is executed, ending the loop immediately.
Another special-circumstance statement you can use inside a loop is continue. The continue statement
causes the loop to exit its current trip through the loop and start over at the first statement of the loop.
Consider the following loop:
int index = 0;
while (index <= 1000) {
index = index + 5;
if (index == 400)
continue;
System.out.println("The index is " + index);
}
In this loop, the statements will be handled normally unless the value of index equals 400. In that
case, the continue statement causes the loop to go back to the while statement instead of proceeding
normally to the System.out.println() statement. Because of the continue statement, the loop will never
display the following text:
You can use the break and continue statements with all three kinds of Java loop statements.
Naming a Loop
Like other statements in Java programs, loops can be put inside of each other. The following shows a
for loop inside a while loop:
int points = 0;
int target = 100;
while (target <= 100) {
for (int i = 0; i < target; i++) {
if (points > 50)
break;
points = points + i;
}
}
In this example, the break statement will cause the for loop to end if the points variable is greater than
50. However, the while loop will never end, because target is never greater than 100.
In this case (and others), you might want to break out of both loops. To make this possible, you have
to give the outer loop—in this example, the while statement—a name. To name a loop, put the name
on the line before the beginning of the loop and follow it with a colon (:).
Once the loop has a name, you can use the name after the break or continue statement to indicate to
which loop the break or continue statement applies. Although the name of the loop is followed by a
colon at the spot where the loop begins, the colon is not used with the name in a break or continue
statement.
The following example repeats the previous one with the exception of one thing: If the points variable
is greater than 50, both loops are ended.
int points = 0;
int target = 100;
targetloop:
while (target <= 100) {
for (int i = 0; i < target; i++) {
if (points > 50)
break targetloop;
points = points + i;
}
}
Most for loops are directly comparable to the ones used up to this point in the hour. They can also be
a little more complex if you want to work with more than one variable in the for statement.
Each section of a for loop is set off from the other sections with a semicolon (;). A for loop can have
more than one variable set up during the initialization section, and more than one statement in the
change section, as in the following:
int i, j;
for (i = 0, j = 0; i * j < 1000; i++, j += 2) {
System.out.println(i + " * " + j + " = " + i * j);
}
These multiple statement sections of the for loop are set off by commas, as in i = 0, j = 0. This loop
will display a list of equations where the i variable is multiplied by the j variable. The i variable
increases by one, and the j variable increases by two during each trip through the loop. Once i
multiplied by j is no longer less than 1,000, the loop will end.
Sections of a for loop can also be empty. An example of this would be if the counter variable has
already been created with an initial value in another part of the program, as in the following:
This hour's workshop provides evidence that you cannot punish your computer in the same way that
Bart Simpson is punished at the beginning of each episode of The Simpsons. Pretend you're a teacher
and the computer is a kid who contaminated your morning cup of coffee with Thorium 230.
Even if you're the most strident liberal, you realize that the computer must be taught a lesson—it's not
acceptable behaviour to give the teacher radiation poisoning. Your computer must be punished, and
the punishment is to display the same sentence over and over again.
The Repeat program will use a loop statement to handle a System.out.println () statement again and
again. Once the computer has been dealt this punishment for 1,000,000 sentences or one minute,
whichever comes first, it can stop running and think about the error of its ways.
A topic of heated debate here at Sams concerns whether the punishment is severe enough. Thorium is
a silver-white metal that has a half-life of 80,000 years. Some scientists believe that it is as toxic as
plutonium, and if it finds a home in someone's liver, bone marrow, or lymphatic tissue, Thorium 230
can cause cancer, leukemia, or lung cancer. A student who irradiates a teacher probably should
receive three hours of in-school detention, at least.
Use your word processor to create a new file called Repeat.java. Enter the text of Listing 8.2 and save
the file when you're done.
1: import java.util.*;
2:
3: class Repeat {
4: public static void main(String[] arguments) {
5: String sentence = "Thorium 230 is not a toy.";
6: int count = 1;
7: Calendar start = Calendar.getInstance ();
8: int startMinute = start.get(Calendar.MINUTE);
9: int startSecond = start.get(Calendar.SECOND);
10: start.roll(Calendar.MINUTE, true);
11: int nextMinute = start.get(Calendar.MINUTE);
12: int nextSecond = start.get(Calendar.SECOND);
13: while (count < 1000000) {
14: System.out.println(sentence);
15: GregorianCalendar now = new GregorianCalendar();
16: if (now.get(Calendar.MINUTE) >= nextMinute)
17: if (now.get(Calendar.SECOND) >= nextSecond)
18: break;
19: count++;
20: }
21: System.out.println("\nI wrote the sentence " + count
22: + " times.");
23: System.out.println("I have learned my lesson.");
24: }
25: }
Line 1: The import statement makes the java.util group of classes available to this program.
You're going to use one of these classes, Calendar, in order to keep track of time while the
program is running.
Lines 3 and 4: The Repeat class is declared, and the main() block of the program begins.
Lines 5 and 6: The sentence variable is set up with the text of the punishment sentence, and
the count variable is created with a value of 1.
Line 7: Using the Calendar class, which keeps track of time-related information, the start
variable is created with the current time as its value.
Lines 8 and 9: The get() method of the Calendar class is used to retrieve the current minute
and second and store them in the variables startMinute and startSecond.
Line 10: The Calendar roll() method is used to roll the value of the start variable one minute
forward in time.
Lines 11 and 12: The get() method is used again to retrieve the minute and second for start
and store them in the variables nextMinute and nextSecond.
Line 13: The while statement begins a loop using the count variable as the counter. When
count hits 1,000,000, the loop will end.
Line 14: The punishment text, stored in the string variable sentence, is displayed.
Line 15: Using the Calendar class, the now variable is created with the current time.
Lines 16–18: Using one if statement inside of another, the program tests to see if one minute
has passed by comparing the current minute and second to the values of nextMinute and
nextSecond. If it has passed, break ends the while loop.
Lines 20–22: The computer displays the number of times it repeated the punishment sentence
and claims to be rehabilitated.
Lines 24 and 25: The main() block of the program and the program are closed out with }
marks.
Compile the program with the javac compiler tool or another compiler and then give it a try. Using the
SDK, you can run it by typing the following at the command line:
java Repeat
Run this program several times to see how many sentences are displayed in a minute's time. The
Repeat program is an excellent way to see whether your computer is faster than mine. During the
testing of this workshop program, Repeat usually displayed around 390,000 sentences in a minute's
time. If your computer displays the sentence more times than mine does, don't just send me your
condolences. Buy more of my books so I can upgrade.
Summary
The information presented in this chapter is material you will be coming back to again and again and
again when you write programs. Loops are a fundamental part of most programming languages. In
several of the hours to come, you get a chance to manipulate graphics so you can produce animated
effects. You couldn't do this without loops.
As you might expect, every one of Bart Simpson's chalkboard punishments has been documented on
the World Wide Web. Visit http://www.snpp.com/guides/chalkboard.openings.html to see the list
along with a Java applet that draws sayings on a green chalkboard.