Java Reference
In-Depth Information
Short-Circuited Evaluation
In this section we will explore the use of the logical operators to solve a complex pro-
gramming task, and we'll introduce an important property of these operators. We will
write a method called firstWord that takes a String as a parameter and returns the
first word in the string. To keep things simple, we will adopt the convention that a
String is broken up into individual words by spaces. If the String has no words at
all, the method should return an empty string. Here are a few example calls:
Method Call
Value Returned
firstWord("four score and seven years")
"four"
firstWord("all-one-word-here")
"all-one-word-here"
firstWord(" lots of space here")
"lots"
firstWord(" ")
""
Remember that we can call the substring method to pull out part of a string. We
pass two parameters to the substring method: the starting index of the substring
and the index one beyond the end of the substring. If the string is stored in a variable
called s , our task basically reduces to the following steps:
set start to the first index of the word.
set stop to the index just beyond the word.
return s.substring(start, stop).
As a first approximation, let's assume that the starting index is 0. This starting
index won't work for strings that begin with spaces, but it will allow us to focus on
the second step in the pseudocode. Consider a string that begins with "four score" .
If we examine the individual characters of the string and their indexes, we find the
following pattern:
0123456789
...
f
o
u
r
s
c
o
re
...
We set start to 0 . We want to set the variable stop to the index just beyond the
end of the first word. In this example, the word we want is "four" , and it extends
from indexes 0 through 3. So, if we want the variable stop to be one beyond the end
of the desired substring, we want to set it to index 4, the location of the first space in
the string.
So how do we find the first space in the string? We use a while loop. We simply
start at the front of the string and loop until we get to a space:
set stop to 0.
while (the character at index stop is not a space) {
increase stop by 1.
}
 
Search WWH ::




Custom Search