Java Reference
In-Depth Information
4
int
number =
0
;
5
6
while
(number <
20
) {
7 number++;
8
if
(number ==
10
|| number ==
11
)
9
continue
;
10 sum += number;
11 }
12
13 System.out.println(
"The sum is "
+ sum);
14 }
15 }
continue
The sum is 189
The program in ListingĀ 5.13 adds integers from
1
to
20
except
10
and
11
to
sum
. With
the
if
statement in the program (line 8), the
continue
statement is executed when
number
becomes
10
or
11
. The
continue
statement ends the current iteration so that the rest of the
statement in the loop body is not executed; therefore,
number
is not added to
sum
when it is
10
or
11
. Without the
if
statement in the program, the output would be as follows:
The sum is 210
In this case, all of the numbers are added to
sum
, even when
number
is
10
or
11
. Therefore,
the result is
210
, which is
21
more than it was with the
if
statement.
Note
The
continue
statement is always inside a loop. In the
while
and
do-while
loops,
the
loop-continuation-condition
is evaluated immediately after the
continue
statement. In the
for
loop, the
action-after-each-iteration
is performed,
then the
loop-continuation-condition
is evaluated, immediately after the
continue
statement.
You can always write a program without using
break
or
continue
in a loop (see Check-
point Question 5.26). In general, though, using
break
and
continue
is appropriate if it
simplifies coding and makes programs easier to read.
Suppose you need to write a program to find the smallest factor other than
1
for an integer
n
(assume
n >= 2
). You can write a simple and intuitive code using the
break
statement as
follows:
int
factor =
2
;
while
(factor <= n) {
if
(n % factor ==
0
)
break
;
factor++;
}
System.out.println(
"The smallest factor other than 1 for "
+ n +
" is "
+ factor);
You may rewrite the code without using
break
as follows:
boolean
found =
false
;
int
factor =
2
;
while
(factor <= n && !found) {
if
(n % factor ==
0
)
Search WWH ::
Custom Search