Java Reference
In-Depth Information
Code 4.6
Finding the first
matching item in a list
else {
// Return where it was found.
return index;
It might be tempting to try to have just one condition in the loop, even though there are two
distinct reasons for ending the search. A way to do this would be to arrange artificially for the
value of index to be too large if we find what we are looking for. This is a practice we discour-
age, because it makes the termination criteria of the loop misleading, and clarity is always to be
Some non-collection examples
Loops are not only used with collections. There are many situations were we want to repeat a
block of statements that does not involve a collection at all. Here is an example that prints out
all even numbers from 0 up to 30:
int index = 0;
while(index <= 30) {
index = index + 2;
In fact, this is the use of a while loop for definite iteration, because it is clear at the start how
many numbers will be printed. However, we cannot use a for-each loop, because they can only
be used when iterating over collections. Later we will meet a third, related loop—the for loop
that would be more appropriate for this particular example.
To test your own understanding of while loops aside from collections, try the following exercises.
Exercise 4.30 Write a while loop (for example, in a method called multiplesOfFive )
that prints out all multiples of 5 between 10 and 95.
Exercise 4.31 Write a while loop to sum the values 1 to 10 and print the sum once the loop
has finished.
Exercise 4.32 Write a method called sum with a while loop that adds up all numbers be-
tween two numbers a and b . The values for a and b can be passed to the sum method as
Exercise 4.33 Challenge task Write a method isPrime(int n) that returns true if the
parameter n is a prime number, and false if it is not. To implement the method, you can write
Search WWH ::

Custom Search