Java Reference
In-Depth Information
and
int index = 0;
boolean found = false;
while(index < files.size() && !found)
Take some time to make sure you understand these two fragments, which accomplish exactly
the same loop control, but expressed in slightly different ways. Remember that the condition
as
a whole
must evaluate to
true
if we want to continue looking, and
false
if we want to stop look-
ing, for any reason. We discussed the “and” operator
&&
in Chapter 3, which only evaluates to
true
if
both
of its operands are
true
.
The full version of a method to search for the first file name matching a given search string
can be seen in Code 4.6 (
music-organizer-v4
). The method returns the index of the item as its
result. Note that we need to find a way to indicate to the method's caller if the search has failed.
In this case, we choose to return a value that cannot possibly represent a valid location in the
collection—a negative value. This is a commonly used technique in search situations: the return
of an
out-of-bounds
value to indicate failure.
Code 4.6
Finding the first
matching item in a list
/**
* Find the index of the first file matching the given
* search string.
* @param searchString The string to match.
* @return The index of the first occurrence, or -1 if
* no match is found.
*/
public
int
findFirst(String searchString)
{
int
index = 0;
// Record that we will be searching until a match is found.
boolean
searching =
true
;
while
(searching && index < files.size()) {
String filename = files.get(index);
if
(filename.contains(searchString)) {
// A match. We can stop searching.
searching =
false
;
}
else
{
// Move on.
index++;
}
}
if
(searching) {
// We didn't find it.
return
-1;
}
Search WWH ::
Custom Search