System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə19/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   15   16   17   18   19   20   21   22   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )

statements;
} while(condition
Although the braces are not necessary when only one statement is present, they are
often used to improve readability of the do­while construct, thus preventing confusion
with the while. The do­while loop executes as long as the conditional expression is
true.
The following program loops until the user enters the letter q:


Using a do­while loop, we can further improve the guessing game program from
earlier in this chapter. This time, the program loops until you guess the letter.
Here is a sample run:


Notice one other thing of interest in this program. There are two do­while loops in the
program. The first loops until the user guesses the letter. Its operation and meaning
should be clear. The second do­while loop, shown again here, warrants some
explanation:
As explained earlier, console input is line buffered—you have to press 
ENTER
before
characters are sent. Pressing 
ENTER
causes a carriage return and a line feed (newline)
sequence to be generated. These characters are left pending in the input buffer. Also, if
you typed more than one key before pressing 
ENTER
, they too would still be in the input
buffer. This loop discards those characters by continuing to read input until the end of
the line is reached. If they were not discarded, then those characters would also be sent
to the program as guesses, which is not what is wanted. (To see the effect of this, you
might try removing the inner do­while loop.) In 
Chapter 10
, after you have learned
more about Java, some other, higher­level ways of handling console input are
described. However, the use of read( ) here gives you insight into how the foundation
of Java's I/O system operates. It also shows another example of Java's loops in action.
Try This 3­2
Improve the Java Help System
This project expands on the Java help system that was created in 
Try This 3­1
. This


version adds the syntax for the for, while, and do­while loops. It also checks the
user’s menu selection, looping until a valid response is entered.
1. Copy Help.java to a new file called Help2.java.
2. Change the first part of main( ) so that it uses a loop to display the choices, as
shown here:
Notice that a nested do­while loop is used to discard any unwanted characters
remaining in the input buffer. After making this change, the program will loop,
displaying the menu until the user enters a response that is between 1 and 5.
3. Expand the switch statement to include the for, while, and do­while loops, as
shown here:


Notice that no default statement is present in this version of the switch. Since the
menu loop ensures that a valid response will be entered, it is no longer necessary to
include a default statement to handle an invalid choice.
4. Here is the entire Help2.java program listing:



USE BREAK TO EXIT A LOOP
It is possible to force an immediate exit from a loop, bypassing any remaining code in
the body of the loop and the loop’s conditional test, by using the break statement.
When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop. Here is a simple
example:
This program generates the following output:
As you can see, although the for loop is designed to run from 0 to num (which in this
case is 100), the break statement causes it to terminate early, when i squared is greater
than or equal to num.
The break statement can be used with any of Java’s loops, including intentionally
infinite loops. For example, the following program simply reads input until the user
types the letter q:


When used inside a set of nested loops, the break statement will break out of only the
innermost loop. For example:
This program generates the following output:


As you can see, the break statement in the inner loop causes the termination of only
that loop. The outer loop is unaffected.
Here are two other points to remember about break. First, more than one break
statement may appear in a loop. However, be careful. Too many break statements have
the tendency to destructure your code. Second, the break that terminates a switch
statement affects only that switch statement and not any enclosing loops.
USE BREAK AS A FORM OF GOTO
In addition to its uses with the switch statement and loops, the break statement can
be employed by itself to provide a “civilized” form of the goto statement. Java does not
have a goto statement, because it provides an unstructured way to alter the flow of
program execution. Programs that make extensive use of the goto are usually hard to
understand and hard to maintain. There are, however, a few places where the goto is a
useful and legitimate device. For example, the goto can be helpful when exiting from a
deeply nested set of loops. To handle such situations, Java defines an expanded form of
the break statement. By using this form of break, you can, for example, break out of
one or more blocks of code. These blocks need not be part of a loop or a switch. They
can be any block. Further, you can specify precisely where execution will resume,
because this form of break works with a label. As you will see, break gives you the
benefits of a goto without its problems.
The general form of the labeled break statement is shown here:
break label;
Typically, label is the name of a label that identifies a block of code. When this form of
break executes, control is transferred out of the named block of code. The labeled
block of code must enclose the break statement, but it does not need to be the
immediately enclosing block. This means that you can use a labeled break statement to
exit from a set of nested blocks. But you cannot use break to transfer control to a block
of code that does not enclose the break statement.
To name a block, put a label at the start of it. The block being labeled can be a stand­
alone block, or a statement that has a block as its target. A label is any valid Java
identifier followed by a colon. Once you have labeled a block, you can then use this label
as the target of a break statement. Doing so causes execution to resume at the end of
the labeled block. For example, the following program shows three nested blocks:


The output from the program is shown here:
Let’s look closely at the program to understand precisely why this output is produced.
When i is 1, the first if statement succeeds, causing a break to the end of the block of
code defined by label one. This causes After block one. to print. When i is 2, the


second if succeeds, causing control to be transferred to the end of the block labeled by
two. This causes the messages After block two. and After block one. to be printed,
in that order. When i is 3, the third if succeeds, and control is transferred to the end of
the block labeled by three. Now, all three messages are displayed.
Here is another example. This time, break is being used to jump outside of a series of
nested for loops. When the break statement in the inner loop is executed, program
control jumps to the end of the block defined by the outer for loop, which is labeled by
done. This causes the remainder of all three loops to be bypassed.
The output from the program is shown here:
Precisely where you put a label is very important—especially when working with loops.
For example, consider the following program:


The output from this program is shown here:
In the program, both sets of nested loops are the same except for one point. In the first
set, the label precedes the outer for loop. In this case, when the break executes, it
transfers control to the end of the entire for block, skipping the rest of the outer loop’s


iterations. In the second set, the label precedes the outer for’s opening curly brace.
Thus, when break stop2 executes, control is transferred to the end of the outer for’s
block, causing the next iteration to occur.
Keep in mind that you cannot break to any label that is not defined for an enclosing
block. For example, the following program is invalid and will not compile:
Since the loop labeled one does not enclose the break statement, it is not possible to
transfer control to that block.
Ask the Expert
Q
: You say that the goto is unstructured and that the break with a label
offers a better alternative. But really, doesn’t breaking to a label, which
might be many lines of code and levels of nesting removed from the
break, also destructure code?
A
: The short answer is yes! However, in those cases in which a jarring change in
program flow is required, breaking to a label still retains some structure. A goto
has none!
USE CONTINUE
It is possible to force an early iteration of a loop, bypassing the loop’s normal control


structure. This is accomplished using continue. The continue statement forces the
next iteration of the loop to take place, skipping any code between itself and the
conditional expression that controls the loop. Thus, continue is essentially the
complement of break. For example, the following program uses continue to help
print the even numbers between 0 and 100:
Only even numbers are printed, because an odd one will cause the loop to iterate early,
bypassing the call to println( ).
In while and do­while loops, a continue statement will cause control to go directly
to the conditional expression and then continue the looping process. In the case of the
for, the iteration expression of the loop is evaluated, then the conditional expression is
executed, and then the loop continues.
As with the break statement, continue may specify a label to describe which
enclosing loop to continue. Here is an example program that uses continue with a
label:


The output from the program is shown here:
As the output shows, when the continue executes, control passes to the outer loop,
skipping the remainder of the inner loop.
Good uses of continue are rare. One reason is that Java provides a rich set of loop
statements that fit most applications. However, for those special circumstances in
which early iteration is needed, the continue statement provides a structured way to
accomplish it.
Try This 3­3
Finish the Java Help System
This project puts the finishing touches on the Java help system that was created in the
previous projects. This version adds the syntax for break and continue. It also allows
the user to request the syntax for more than one statement. It does this by adding an
outer loop that runs until the user enters q as a menu selection.


1. Copy Help2.java to a new file called Help3.java.
2. Surround all of the program code with an infinite for loop. Break out of this loop,
using break, when a letter q is entered. Since this loop surrounds all of the program
code, breaking out of this loop causes the program to terminate.
3. Change the menu loop as shown here:
Notice that this loop now includes the break and continue statements. It also accepts
the letter q as a valid choice.
4. Expand the switch statement to include the break and continue statements, as
shown here:
5. Here is the entire Help3.java program listing:



6. Here is a sample run:


NESTED LOOPS


NESTED LOOPS
As you have seen in some of the preceding examples, one loop can be nested inside of
another. Nested loops are used to solve a wide variety of programming problems and
are an essential part of programming. So, before leaving the topic of Java’s loop
statements, let’s look at one more nested loop example. The following program uses a
nested for loop to find the factors of the numbers from 2 to 100:
Here is a portion of the output produced by the program:


In the program, the outer loop runs i from 2 through 100. The inner loop successively
tests all numbers from 2 up to i, printing those that evenly divide i. Extra challenge:
The preceding program can be made more efficient. Can you see how? (Hint: The
number of iterations in the inner loop can be reduced.)

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   15   16   17   18   19   20   21   22   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə