Java Reference
In-Depth Information
the test on the length of the string. So these tests also have to be reversed to take
advantage of short-circuited evaluation:
int start = 0;
while (start < s.length() && s.charAt(start) == ' ') {
start++;
}
To combine these lines of code with our previous code, we have to change the ini-
tialization of stop . We no longer want to search from the front of the string. Instead,
we need to initialize stop to be equal to start . Putting these pieces together, we get
the following version of the method:
public static String firstWord(String s) {
int start = 0;
while (start < s.length() && s.charAt(start) == ' ') {
start++;
}
int stop = start;
while (stop < s.length() && s.charAt(stop) != ' ') {
stop++;
}
return s.substring(start, stop);
}
This version works in all cases, skipping any leading spaces and returning an
empty string if there is no word to return.
Boolean Variables and Flags
All if/else statements are controlled by Boolean tests. The tests can be boolean
variables or Boolean expressions. Consider, for example, the following code:
if (number > 0) {
System.out.println("positive");
} else {
System.out.println("not positive");
}
This code could be rewritten as follows:
boolean positive = (number > 0);
if (positive) {
System.out.println("positive");
} else {
System.out.println("not positive");
}
 
Search WWH ::




Custom Search