Java Reference
In-Depth Information
The break on line 21 refers to its enclosing loop, which is the
for
loop on line 18. The
while
loop executes 10 times, and for each value of
x
the
for
loop executes three times
(when
y
is
10
,
9
, and
8
). The output is
1 10 9 8 2 10 9 8 3 10 9 8 4 10 9 8 5 10 9 8 6 10 9 8 7 10 9 8 8 10 9
8 9 10 9 8 10 10 9 8
If we want the outer
while
loop to break on line 21 instead of the inner
for
loop, we
need to use a label as shown here:
25. int x = 1, y = 10;
26. loopx : while(x <= 10) {
27. System.out.print(x++ + “ “);
28. for( ; y >= 1; y--) {
29. System.out.print(y + “ “);
30. if(y == 8)
31. break loopx;
32. }
33. }
The
break
statement on line 31 refers to the
while
loop on line 26. The
while
loop
terminates during its fi rst iteration when
y
becomes
8
, so the output of this code is
1 10 9 8
You can also use labels with the
continue
keyword, which we discuss next.
The
continue
Statement
The exam objectives state that you should be able to “develop code that implements all
forms of loops and iterators, including the use of continue.” A
continue statement
within
a repetition control structure transfers fl ow of control to the loop-continuation point of
the loop. The control structures that can contain a
continue
statement together with their
corresponding continuation point follow:
for
: Control transfers to the update expression of the
for
statement.
while
: Control transfers to the
boolean
expression.
do
: Control transfers to the
boolean
expression.
Figure 3.8 shows the syntax for the
continue
statement within a
for
loop.
Search WWH ::
Custom Search