Repeating an Action with Loops - Learning the Basics of Programming - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part II: Learning the Basics of Programming

Hour 8. Repeating an Action with Loops

THIS HOUR’S TO-DO LIST:

Image Use the for loop.

Image Use the while loop.

Image Use the do-while loop.

Image Exit a loop prematurely.

Image Name a loop.

One of the more annoying punishments for schoolchildren is to make them write something over and over again on a chalkboard. On The Simpsons, in one of his frequent trips to the board, Bart Simpson had to write, “Organ transplants are best left to professionals,” dozens of times. This punishment might work on children but would be completely useless on a computer. A computer program can repeat a task with ease.

Programs are ideally suited to do the same thing over and over because of loops. A loop is a statement or block that is repeated in a program. Some loops run a fixed number of times. Others run indefinitely.

There are three loop statements in Java: for, do, and while. Each can work like the others, but it’s beneficial to learn how all three operate. You often can simplify a loop section of a program by choosing the right statement.

for Loops

In your programming, you find many circumstances in which a loop is useful. You can use them to keep doing something several times, such as when an antivirus program opens each new email as it comes in to look for viruses. You also can use loops to cause the computer to do nothing for a brief period, such as an animated clock that displays the current time once per minute.

A loop statement causes a computer program to return to the same place more than once, like a stunt plane completing an acrobatic loop.

Java’s most complex loop statement is for. A for loop repeats a section of a program a fixed number of times. The following is an example:

for (int dex = 0; dex < 1000; dex++) {
if (dex % 12 == 0) {
System.out.println("#: " + dex);
}
}

This loop displays every number from 0 to 999 that is evenly divisible by 12.

Every for loop has a variable that determines when the loop should begin and end. This variable is called the counter (or index). The counter in the preceding loop is the variable dex.

The example illustrates the three parts of a for statement:

Image The initialization section—In the first part, the dex variable is given an initial value of 0.

Image The conditional section—In the second part, there is a conditional test like one you might use in an if statement: dex < 1000.

Image The change section—The third part is a statement that changes the value of the dex variable, in this example by using the increment operator.

In the initialization section, you set up the counter variable. You can create the variable in the for statement, as the preceding example does with the integer variable dex. You also can create the variable elsewhere in the program. In either case, you should give the variable a starting value in this section of the for statement. The variable has this value when the loop starts.

The conditional section contains a test that must remain true for the loop to continue looping. When the test is false, the loop ends. In this example, the loop ends when the dex variable is equal to or greater than 1,000.

The last section of the for statement contains a statement that changes the value of the counter variable. This statement is handled each time the loop goes around. The counter variable has to change in some way or the loop never ends. In the example, dex is incremented by one in the change section. If dex was not changed, it would stay at its original value of 0 and the conditional dex < 1000 always would be true.

The for statement’s block is executed during each trip through the loop.


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 called an iterator.


The preceding example had the following statements inside the for block:

if (dex % 12 == 0) {
System.out.println("#: " + dex);
}

These statements are executed 1,000 times. The loop starts by setting the dex variable equal to 0. During each pass through the loop, it adds 1 to dex. When dex is no longer less than 1,000, the loop stops looping.

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:

for (int p = 0; p < 500; p++)
System.out.println("I will not sell miracle cures");

This loop displays the text “I will not sell miracle cures” 500 times. Although brackets are not required around a single statement inside a loop, you can use them to make the block easier to spot, like so:

for (int p = 0; p < 500; p++) {
System.out.println("I will not sell miracle cures");
}

The first program you create during this hour displays the first 200 multiples of 9: 9, 18, 27, and so on, up to 1,800 (9 × 200). In NetBeans, create a new empty Java file named Nines and enter the text of Listing 8.1. When you save the file, it is stored as Nines.java.

LISTING 8.1 The Full Text of Nines.java


1: package com.java24hours;
2:
3: class Nines {
4: public static void main(String[] arguments) {
5: for (int dex = 1; dex <= 200; dex++) {
6: int multiple = 9 * dex;
7: System.out.print(multiple + " ");
8: }
9: System.out.println();
10: }
11: }


The Nines program contains a for statement in Line 5. This statement has three sections:

Image Initialization section—int dex = 1, which creates an integer variable called dex and gives it an initial value of 1.

Image Conditional section—dex <= 200, which must be true during each trip through the loop. When it is not true, the loop ends.

Image Change section—dex++, which increments the dex variable by 1 during each trip through the loop.

Run the program by choosing Run, Run File in NetBeans. The program produces the output shown in Figure 8.1.

Image

FIGURE 8.1 The output of the Nines program.

The output window in NetBeans does not wrap text, so all the numbers appear on a single line. To make the text wrap, right-click the Output pane and choose Wrap Text from the pop-up menu.

while Loops

The while loop does not have as many different sections as a 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:

while (gameLives > 0) {
// the statements inside the loop go here
}

This loop continues repeating until the gameLives 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. If the tested condition is false when a program reaches the while statement for the first time, the statements inside the loop are 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 keeps looping forever.

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("Pork is not a verb");
count++;
}

A while loop uses one or more variables 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 “Pork is not a verb” four times. If you gave the count variable an initial value of 6 instead of 1, the text never would be displayed.

do-while Loops

The do-while loop is similar 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 while loop, this loop continues 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 while are handled automatically, and 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 continues indefinitely. The statements inside a do-while loop always are 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("I am not allergic to long division");
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 “I am not allergic to long division” 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.

In a do-while loop, the statements inside the loop are executed at least once even if the loop condition is false the first time around.

Exiting a Loop

The normal way to exit a loop is for the tested condition to become false. This is true of all three types of loops in Java. There might be times when you want a loop to end immediately, even if the condition being tested is still true. You can accomplish this with a break statement, as shown in the following code:

int index = 0;
while (index <= 1000) {
index = index + 5;
if (index == 400) {
break;
}
}

A break statement ends the loop that contains the statement.

In this example, the while loop loops until 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 are 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 continuestatement, the loop never displays the following text:

The index is 400

You can use the break and continue statements with all three kinds of loops.

The break statement makes it possible to create a loop in your program that’s designed to run forever, as in this example:

while (true) {
if (quitKeyPressed == true) {
break;
}
}

Naming a Loop

Like other statements in Java programs, loops can be placed inside other loops. 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 causes the for loop to end if the points variable is greater than 50. However, the while loop never ends because target is never greater than 100.

In some cases, 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 (:).

When the loop has a name, use the name after the break or continue statement to indicate the loop to which the break or continue statement applies. The following example repeats the previous one with the exception of one thing: If the points variable is greater than 50, both loops end.

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;
}
}

When a loop’s name is used in a break or continue statement, the name does not include a colon.

Complex for Loops

A for loop can be more complex, including more than one variable in its initialization, conditional, and change sections. 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 code:

int i, j;
for (i = 0, j = 0; i * j < 1000; i++, j += 2) {
System.out.println(i + " * " + j + " = " + (i * j));
}

In each section of the for loop, commas are used to separate the variables, as in i = 0, j = 0. The example loop displays a list of equations where the i and j variables are multiplied together. The i variable increases by 1, and the j variable increases by 2 during each trip through the loop. When i multiplied by j is equal to or greater than 1,000, the loop ends.

Sections of a for loop also can be empty. An example of this is when a loop’s counter variable already has been created with an initial value in another part of the program, as in the following:

int displayCount = 1;
int endValue = 13;
for ( ; displayCount < endValue; displayCount++) {
// loop statements would be here
}

Testing Your Computer Speed

This hour’s next project is a Java program that performs a benchmark, a test that measures how fast computer hardware or software is operating. The Benchmark program uses a loop statement to repeatedly perform the following mathematical expression:

double x = Math.sqrt(index);

This statement calls the Math.sqrt() method to find the square root of a number. You learn how methods work during Hour 11, “Describing What Your Object Is Like.”

The benchmark you’re creating sees how many times a Java program can calculate a square root in one minute.

Use NetBeans to create a new empty Java file called Benchmark. Enter the text of Listing 8.2 and save the program when you’re done.

LISTING 8.2 The Full Source Code of Benchmark.java


1: package com.java24hours;
2:
3: class Benchmark {
4: public static void main(String[] arguments) {
5: long startTime = System.currentTimeMillis();
6: long endTime = startTime + 60000;
7: long index = 0;
8: while (true) {
9: double x = Math.sqrt(index);
10: long now = System.currentTimeMillis();
11: if (now > endTime) {
12: break;
13: }
14: index++;
15: }
16: System.out.println(index + " loops in one minute.");
17: }
18: }


The following things take place in the program:

Image Lines 3–4—The Benchmark class is declared and the main() block of the program begins.

Image Line 5—The startTime variable is created with the current time in milliseconds as its value, measured by calling the currentTimeMillis() method of Java’s System class.

Image Line 6—The endTime variable is created with a value 60,000 higher than startTime. Since one minute equals 60,000 milliseconds, this sets the variable one minute past startTime.

Image Line 7—A long named index is set up with an initial value of 0.

Image Line 8—The while statement begins a loop using true as the conditional, which causes the loop to continue forever (in other words, until something else stops it).

Image Line 9—The square root of index is calculated and stored in the x variable.

Image Line 10—Using currentTimeMillis(), the now variable is created with the current time.

Image Lines 11–13—If now is greater than endTime, this signifies that the loop has been running for one minute and break ends the while loop. Otherwise, it keeps looping.

Image Line 14—The index variable is incremented by 1 with each trip through the loop.

Image Line 16—Outside the loop, the program displays the number of times it performed the square root calculation.

The output of the application is shown in the Output pane in Figure 8.2.

Image

FIGURE 8.2 The output of the Benchmark program.

The Benchmark program is an excellent way to see whether your computer is faster than mine. During the testing of this program, my laptop performed around 2.9 billion calculations. If your computer has better results, don’t just send me your condolences. Buy more of my books so I can upgrade.

Summary

Loops are a fundamental part of most programming languages. Animation created by displaying several graphics in sequence is one of many tasks you could not accomplish in Java or any other programming language without loops.

Every one of Bart Simpson’s chalkboard punishments has been documented on the Web. Visit www.snpp.com/guides/chalkboard.openings.html to see the list.

That page also contains a Java applet by Don Del Grande that draws one of Bart’s sayings at random on a green chalkboard. The source code for the applet also is available, so you can see how the animation was achieved.

Workshop

Q&A

Q. The term “initialization” has been used in several places. What does it mean?

A. It means to give something an initial value and set it up. When you create a variable and assign a starting value to it, you are initializing the variable.

Q. If a loop never ends, how does the program stop running?

A. Usually in a program where a loop does not end, something else in the program is set up to stop execution in some way. For example, a loop in a game program could continue indefinitely while the player still has lives left.

One bug that crops up often as you work on programs is an infinite loop, a loop that never stops because of a programming mistake. If one of the Java programs you run is stuck in an infinite loop, press the red alert icon to the left of the Output pane.

Q. How can I buy stock in the Green Bay Packers?

A. Unless the publicly owned NFL team decides to hold another stock sale, the only way to become a stockholder is to inherit shares in a will.

The Packers have sold stock in 1923, 1935, 1950, 1997, and 2011. Approximately 364,000 people own 5 million shares in the team, despite the fact that they have very limited rights associated with the stock.

Holders don’t earn a dividend and can’t profit from their shares. They only can sell them back to the team and lose money in the deal. No individual can own more than 200,000 shares.

They do receive exclusive team merchandise offers and can attend an annual meeting to elect the seven-member board that manages the team.

In the 1923 stock sale that formed the franchise, 1,000 fans bought shares for $5 each. The 2011 sale raised $67 million for an upgrade to Lambeau Field, the team’s stadium.

More information on the stock can be found on the Web at www.packers.com/community/shareholders.html.

Quiz

The following questions test your knowledge of loops. In the spirit of the subject matter, repeat each of these until you get them right.

1. What must be used to separate each section of a for statement?

A. Commas

B. Semicolons

C. Off-duty police officers

2. Which statement causes a program to go back to the statement that began a loop and then keep going from there?

A. continue

B. next

C. skip

3. Which loop statement in Java always runs at least once?

A. for

B. while

C. do-while

Answers

1. B. Commas are used to separate things within a section, but semicolons separate sections.

2. A. The break statement ends a loop entirely, and continue skips to the next go-round of the loop.

3. C. The do-while conditional isn’t evaluated until after the first pass through the loop.

Activities

If your head isn’t going in circles from all this looping, review the topics of this hour with the following activities:

Image Modify the Benchmark program to test the execution of simple mathematical calculation, such as multiplication or division.

Image Write a short program using loops that finds the first 400 numbers that are multiples of 13.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.