In addition to being able to apply conditions to your programs and see different outcomes based on various
if
/then
scenarios, you sometimes
want your code to do the same thing over and over again until the job is done. In
this section, learn about two constructs used to iterate over code or execute it
more than once: for
loops and while
loops. What is a loop?
A loop is a programming construct that executes repeatedly while some condition (or set of conditions) is met. For instance, you might ask a program to read all records until the end of a file, or loop over all the elements of an array, processing each one. (You learn about arrays in this tutorial's "Java Collections" section.)
for
loops
The basic loop construct in the Java language is the for
statement,
which you can use to iterate over a range of values to determine how many times to
execute a loop. The abstract syntax for a for
loop is:
1
2
3
| for (initialization; loopWhileTrue; executeAtBottomOfEachLoop) { statementsToExecute } |
loopWhileTrue
(a Java conditional expression that must
evaluate to either true or false) is true, the loop executes. At the bottom of the
loop, executeAtBottomOfEachLoop
executes.
Example of a for
loop
If you wanted to change a main()
method to execute three times, you can
use a for
loop, as shown in Listing 8.
Listing 8. A for
loop
1
2
3
4
5
6
7
8
9
10
11
12
13
| public static void main(String[] args) { Logger l = Logger.getLogger(Person.class.getName()); for (int aa = 0; aa < 3; aa++) { Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); l.info("Loop executing iteration# " + aa); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); } } |
aa
is initialized to zero at the beginning of Listing 8. This statement executes only once, when the loop
is initialized. The loop then continues three times, and each time aa
is incremented by one. As you'll see later, an alternate
for
loop syntax is available for
looping over constructs that implement the Iterable
interface (such as
arrays and other Java utility classes). For now, just note the use of the
for
loop syntax in Listing 8.
while
loops
The syntax for a while
loop is:
1
2
3
| while (condition) { statementsToExecute } |
while condition
evaluates to true, so
the loop executes. At the top of each iteration (that is, before any statements
execute), the condition is evaluated. If the condition evaluates to true, the loop
executes. So it's possible that a while
loop will never execute if its
conditional expression is not true at least once. Look again at the
for
loop in Listing 8. For
comparison, Listing 9 uses a while
loop to obtain the same result.
Listing 9. A while
loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public static void main(String[] args) { Logger l = Logger.getLogger(Person.class.getName()); int aa = 0; while (aa < 3) { Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); l.info("Loop executing iteration# " + aa); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); aa++; } } |
while
loop requires a bit more housekeeping than a
for
loop. You must initialize the aa
variable and also
remember to increment it at the bottom of the loop.
do...while
loops
If you want a loop that always executes once and then checks its conditional
expression, try using a do...while
loop, as shown in Listing 10.
Listing 10. A do...while
loop
1
2
3
4
5
6
7
8
9
10
11
12
| int aa = 0; do { Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); l.info("Loop executing iteration# " + aa); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); aa++; } while (aa < 3); |
aa < 3
) is not checked until the end of
the loop. Loop branching
At times, you need to bail out of a loop before the conditional expression evaluates to false. This situation can occur if you are searching an array ofString
s for a particular value, and once you find it, you don't
care about the other elements of the array. For the times when you want to bail, the
Java language provides the break
statement, shown in Listing 11.
Listing 11. A break
statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| public static void main(String[] args) { Logger l = Logger.getLogger(Person.class.getName()); int aa = 0; while (aa < 3) { if (aa == 1) break; Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); l.info("Loop executing iteration# " + aa); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); aa++; } } |
break
statement takes you to the next executable statement outside
of the loop in which it's located. Loop continuation
In the (simplistic) example in Listing 11, you only want to execute the loop once and bail. You can also skip a single iteration of a loop but continue executing the loop. For that purpose, you need thecontinue
statement, shown in Listing 12.
Listing 12. A continue
statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| public static void main(String[] args) { Logger l = Logger.getLogger(Person.class.getName()); int aa = 0; while (aa < 3) { if (aa == 1) continue; else aa++; Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); l.info("Loop executing iteration# " + aa); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); } } |
continue
comes in handy when you are, say,
processing records and come across a record you definitely don't want to process.
You can skip that record and move on to the next one.
0 comments:
Post a Comment