Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

102 HOUR 8: Repeating an Action with Loops


int points = 0;
int target = 100;
targetLoop:
while(target <= 100) {
for (int i = 0; i < target; i++) {
if (points > 50)
breaktargetLoop;
points = points + i;
}
}

When a loop’s name is used in a breakor continuestatement, the name
does not include a colon.

ComplexforLoops
Aforloop can be more complex, including more than one variable in its
initialization, conditional, and change sections. Each section of a forloop
is set off from the other sections with a semicolon(;). Aforloop 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 forloop, commas are used to separate the variables
as in i = 0, j = 0. The example loop displays a list of equations where
the iand jvariables are multiplied together. The ivariable increases by
one, and the jvariable increases by two during each trip through the loop.
When imultiplied by jis equal or greater than 1,000, the loop ends.
Sections of a forloop also canbe 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:
for ( ; displayCount < endValue; displayCount++) {
// loop statements would be here
}

Testing Your Computer Speed
This hour’s workshop is a Java program that performs a benchmark, a test
that measures how fast computer hardware or software is operating. The
Free download pdf