Java Reference
In-Depth Information
This is easily converted into Java code. Combining it with our assumption that
start will be 0 , we get:
public static String firstWord(String s) {
int start = 0;
int stop = 0;
while (s.charAt(stop) != ' ') {
stop++;
}
return s.substring(start, stop);
}
This version of the method works for many cases, including our sample string, but
it doesn't work for all strings. It has two major limitations. We began by assuming
that the string did not begin with spaces, so we know we have to fix that limitation.
The second problem is that this version of firstWord doesn't work on one-word
strings. For example, if we execute it with a string like "four" , it generates a
StringIndexOutOfBoundsException indicating that 4 is not a legal index. The
exception occurs because our code assumes that we will eventually find a space, but
there is no space in the string "four" . So stop is incremented until it becomes equal
to 4 , and an exception is thrown because there is no character at index 4. This is
sometimes referred to as “running off the end of the string.”
To address this problem, we need to incorporate a test that involves the length of
the string. Many novices attempt to do this by using some combination of while and
if , as in the following code:
int stop = 0;
while (stop < s.length()) {
if (s.charAt(stop) != ' ') {
stop++;
}
}
This code works for one-word strings like "four" because as soon as stop
becomes equal to the length of the string, we break out of the loop. However, it doesn't
work for the original multiword cases like "four score" . We end up in an infinite
loop because once stop becomes equal to 4 , we stop incrementing it, but we get
trapped inside the loop because the test says to continue as long as stop is less than
the length of the string. This approach of putting an if inside a while led to a world-
famous bug on December 31, 2008, when Zune music players all over the world
stopped working (see Programming Exercise 21 for more details).
The point to recognize is that in this case we need to use two different conditions
in controlling the loop. We want to continue incrementing stop only if we know that
 
Search WWH ::




Custom Search