Java Reference
In-Depth Information
The continue and break statements . Java has a continue statement , whose execution causes ter-
mination of the repetend of a loop. It also has a break statement , whose execu-
tion causes termination of a loop or a switch statement. For information on these
statements, look at the ProgramLive glossary as well as lesson page 7-6.
Another possibility for the loop condition of this loop is i<n . In this section, we
discuss the two possible loop conditions. We have two reasons for preferring
condition i != n.
Reason 1. It is easier to develop i!=n , rather than i<n , using
our guidelines. We find a relation that indicates when the loop can
stop and complement it to get the loop condition.
Reason 2. Using i!=n can lead to earlier detection of errors.
To understand the second reason, consider the following scenario. Suppose
someone has to change this program, perhaps because of a modification in its
specification to meet some new need, and they make a mistake that leads to i
becoming greater than n . With the loop condition i<n , the loop terminates; with
the condition i!=n , the loop does not stop at all. Under these conditions, which
loop condition do you prefer?
With the error in the program, the loop condition i<n would cause the loop
to terminate. The error might go undetected and might never exhibit itself. When
the program is used later, the error could lead to unknowingly wrong output or
even to a plane crash.
But with the condition i!=n , the program is in an infinite loop, and the pro-
grammer will certainly notice the problem and fix it immediately.
7.6.2
A case where i < n is needed
We develop a program to produce the reverse of a String t . Thus, if variable t
initially contains the value "abcde" , upon termination t contains "edcba" .
Unfortunately, one cannot change the value of a String object; it is immu-
table . The standard procedure in this case is to copy the String into a variable s
of class StringBuffer , which can be changed (is mutable ), operate on s , and
then assign s to t . See Sec. 5.2.5 for information on class StringBuffer .
Here is the outline of the program segment:
Activity
7-5.3
StringBuffer s= new StringBuffer(t);
Set s to the reverse of s ;
t= s.toString();
Here is an idea for reversing s . The first and last characters of s have to be
swapped, so we could do this first. Now, the outer two characters are in their final
positions, and the next two outer characters can be swapped. And then the next
two outer characters, and so on:
Search WWH ::




Custom Search