Java Reference
In-Depth Information
Scope of do Variables
A variable declared within the block of a do statement only has scope within that block.
Be aware that the boolean expression of a do statement is outside the block, so the
following code does not compile:
17. do {
18. int one = rollDice();
19. int two = rollDice();
20. System.out.println(“You rolled a “ + (one + two));
21. }while(one + two != 11);
The variables one and two are out of scope on line 21. For this loop to work, one and two
need to be declared outside of the do statement.
Now that we have discussed the various looping control structures in Java, I want to discuss
two important keywords that affect the fl ow of control of loops: break and continue . Let's
start with a discussion of the break statement.
The break 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 break.” A break statement transfers
fl ow of control out of an enclosing statement. A break statement can appear within the
following control structures:
switch
for
while
do
Figure 3.7 shows the syntax for a break statement within a while statement. (The
syntax is similar for the other control structures.)
Search WWH ::




Custom Search