Java Reference
In-Depth Information
You scan the string, str , in the while loop. The loop continues as long as there is another token available
from the string. Within the loop, you check for the presence of a token defined by regex by calling the
hasNext() method with the had pattern as the argument:
if(strScan.hasNext(had)) {
++hadCount;
System.out.println("Token found!: " + strScan.next(had));
} else {
System.out.println("Token is : " + strScan.next());
}
If hasNext() returns true , you increment hadCount and output the token returned by next() with the
argument as had . Of course, you could just as well have used the next() method with no argument here.
If the next token does not correspond to had , you read it anyway with the next() method. Finally, you
output the number of times your token was found.
From the output you can see that only four instances of "had" were found. This is because the scanner
assumes the delimiter is one or more whitespace characters. If you don't like this you can specify another
regular expression that the scanner should use for the delimiter:
strScan.useDelimiter("[^\\w*]");
The useDelimiter() method expects an argument of type String that specifies a regular expression for
recognizing delimiters. In this case the expression implies a delimiter is any number of characters that
are not uppercase or lowercase letters, or digits. If you add this statement following the creation of the
Scanner object the program should find all the "had" tokens.
SUMMARY
This chapter has been a brief canter through some of the interesting and useful classes available in the
java.util package. The ones I chose to discuss are those that seem to me to be applicable in a wide range
of application contexts, but there's much more to this package than I have had the space to discuss here. You
should find it is a rewarding exercise to delve into the contents of this package a little further.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Define a static method to fill an array of type char[] with a given value passed as an argument to
the method.
2. For the adventurous gambler — use a stack and a Random object in a program to simulate a game of
Blackjack for one player using two decks of cards.
3. Write a program to display the sign of the Zodiac corresponding to a birth date entered through the
keyboard.
Search WWH ::




Custom Search