ptg7068951
104 HOUR 8: Repeating an Action with Loops
. Line 6: The whilestatement begins a loop using trueas the condi-
tional, which causes the loop to continue forever (in other words,
until something else stops it).
. Line 7: The square root of indexis calculated and stored in the x
variable.
. Line 8: Using currentTimeMillis(), the nowvariable is created with
the current time.
. Lines 9–11: If nowis greater than endTime, this signifies that the loop
has been running for one minute and breakends the whileloop.
Otherwise, it keeps looping.
. Line 12: The indexvariable is incremented by 1 with each trip
through the loop.
. Lines 14: 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.1.
FIGURE 8.1
The output of the Benchmark
program.
The Benchmarkprogram is an excellent way to see whether your computer is
faster than mine. During the testing of this program, my computer performed
around 4.5 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 document-
ed on the Web. Visit http://www.snpp.com/guides/chalkboard.openings.html to
see the list along with a Java program that runs on the page drawing Bart’s
sayings on a green chalkboard.