Java Reference
In-Depth Information
Try to express the second version by completing the following outline:
boolean found = false;
while(...) {
if( the keys are in the next place ) {
...
}
}
4.10.2
Iterating with an index variable
For our first while loop in correct Java code, we shall write a version of the listAllFiles
method shown in Code 4.3. This does not really illustrate the indefinite character of while
loops, but it does provide a useful comparison with the equivalent, familiar for-each example.
The while-loop version is shown in Code 4.5. A key feature is the way that an integer variable
( index ) is used both to access the list's elements and to control the length of the iteration.
Code 4.5
Using a while loop
to list the tracks
/**
* Show a list of all the files in the collection.
*/
public void listAllFiles()
{
int index = 0;
while (index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
index++;
}
}
It is immediately obvious that the while-loop version requires more effort on our part to pro-
gram it. Consider:
We have to declare a variable for the list index, and we have to initialize it ourselves to 0 for
the first list element. The variable must be declared outside the loop.
We have to work out how to express the loop's condition in order to ensure that the loop
stops at the right time.
The list elements are not automatically fetched out of the collection and assigned to a vari-
able for us. Instead, we have to do this ourselves, using the get method of the ArrayList .
The variable filename will be local to the body of the loop.
We have to remember to increment the counter variable ( index ) ourselves, in order to ensure
that the loop condition will eventually become false when we have reached the end of the list.
 
Search WWH ::




Custom Search