Java Reference
In-Depth Information
and proceeds with the next iteration of the loop. In a
while
or
do
...
while
structure,
the
logical expression
is evaluated immediately after the
continue
statement. In a
for
structure, the
update statement
is executed after the
continue
statement, and
then the
logical expression
executes.
If the previous program segment encounters a negative number, the
while
loop termi-
nates. If you want to ignore the negative number and read the next number rather than
terminate the loop, replace the
break
statement with the
continue
statement, as shown
in the following example:
sum = 0;
while
(console.hasNext())
{
5
num = console.nextInt();
if
(num < 0)
//if the number is negative, go to the
//next iteration
{
System.out.println("Negative number found in the data.");
continue
;
}
sum = sum + num;
}
The
break
and
continue
statements are an effective way to avoid extra variables to control
a loop and produce an elegant code. However, these statements must be used very sparingly
within a loop. An excessive use of these statements in a loop will produce a spaghetti-code
(loops with many exit conditions) and could be very hard to understand and manage.
As stated earlier, all three loops have their place in Java and one loop can often replace
another. The execution of a
continue
statement, however, is where a
while
structure
differs from a
for
structure. In a
while
loop, when the
continue
statement is executed,
if the
update statement
appears after the
continue
statement, the
update
statement
is not executed. In a
for
loop, the
update statement
always executes.
Debugging sections in the previous chapters illustrated how to debug syntax and logical
errors, and how to avoid partially understood concepts. In this section, we illustrate how
to avoid a software patch to fix a code. A software patch is a piece of code written on top
of an existing piece of code intended to fix a bug in the original code.
DEBUGGING
Search WWH ::
Custom Search