Java Reference

In-Depth Information

7.4.5

Self-review exercises

SR1
. The range in the schema in Fig. 7.2 can be generalized. Rewrite it so that

it processes the natural numbers in the range
i..j-1
rather than
0..n-1
.

SR2
. Use the schema in Fig. 7.2 to write a loop to find the number of vowels in

a
String s
. Hint: declare a new
String
that contains the five vowels, and use

the fact that
String
method
indexOf
returns
-1
if the
char
argument is not in

the
String
of vowels.

SR3
. How many numbers are there in the range
i..j-1
?

Answers to self review exercises

SR1.
//
Process the natural numbers
i..j-1
(for
j≥i)

int
k= i;

// {
invariant:
i..k-1
have been processed
}

while
(k != j) {

Process
k;

k= k + 1;

}

// {i..j-1
have been processed
}

SR2.
//
Set
x
to the number of vowels in
s[0..s.length()-1]

int
k= 0; x= 0;

String vowels = "aeiou";

// {
invariant:
x
= number of vowels in
s[0..k-1] }

while
(k != s.length()) {

if
(vowels.indexOf(s.charAt(k)) != -1) {

x= x + 1;

}

k= k + 1;

}

// { x =
number of
vowels
in
s[0..s.length()-1] }

SR3.
j-i+1

7.5

The for-loop

7.5.1

The for-loop as an abbreviation

Besides the while-loop, Java has an iterative statement called the
for-loop
. The

for-loop can be viewed as an abbreviation of a certain kind of while-loop. Here

is an example. The following loop draws
n
concentric circles:

Activity

7-4.1

Search WWH ::

Custom Search