Java Reference
In-Depth Information
Notice that the
do
statement includes a semicolon. A typical use of the
do
statement is shown in the following pseudocode fragment:
do
{
Prompt user;
Read value;
} while( value is no good );
The
do
statement is by far the least frequently used of the three looping
constructs. However, when we have to do something at least once, and for
some reason a
for
loop is inappropriate, then the
do
statement is the method of
choice.
1.5.7
break
and
continue
The
for
and
while
statements provide for termination before the start of a
repeated statement. The
do
statement allows termination after execution of a
repeated statement. Occasionally, we would like to terminate execution in the
middle of a repeated (compound) statement. The
break
statement, which is
the keyword
break
followed by a semicolon, can be used to achieve this.
Typically, an
if
statement would precede the
break
, as in
while( ... )
{
...
if( something )
break;
...
}
The
break
statement exits the innermost loop only (it is also used in conjunc-
tion with the
switch
statement, described in the next section). If there are several
loops that need exiting, the
break
will not work, and most likely you have poorly
designed code. Even so, Java provides a labeled
break
statement. In the labeled
break
statement, a loop is labeled, and then a
break
statement can be applied to the
loop, regardless of how many other loops are nested. Here is an example:
The
break
state-
ment exits the
innermost loop or
switch
statement.
The labeled
break
statement exits
from a nested loop.
outer:
while( ... )
{
while( ... )
if( disaster )
break
outer; // Go to after outer
}
// Control passes here after outer loop is exited
Search WWH ::
Custom Search