exercise it is only necessary that both versions accept the same correctly formatted input.
Exercise 22.13: Extend your solution to Exercise 22.12 so that misplaced = characters are detected, as in the
StreamTokenizer version. (Hint: You might want to try to dynamically change the delimiter pattern
between certain tokens.)
22.5.4. Localization
Localization is covered in detail in Chapter 24, but since the Scanner class has some support for
localization, we cover that briefly here.
By default a scanner works in the current locale, but you can change it with the useLocale method, which
takes a Locale instance. The locale being used by the scanner can be retrieved from the locale method.
The type-specific numeric scanning methods, like hasNextDouble and nextInt, are fully localized.
They recognize numerical values that are formed from the numeric digit characters of the locale being used,
including the locale-specific decimal separator and grouping separator. In contrast, to use a regular expression
to match a local number, you would need to know what the separator characters were so that you could
account for them in your pattern. Further, any potentially numeric value that is obtained as a string from a
MatchResult must be separately converted into a numeric value. To localize such numeric values you must
use the parsing methods of the java.text.NumberFormat class described in Chapter 24.
22.6. StringTokenizer
The StringTokenizer class is an older and much simpler cousin of the Scanner class, and its use is
discouraged in new codethe Stringsplit method (page 314) can be used as an alternative in many cases.
A StringTokenizer breaks a string into parts, using delimiter characters. A sequence of tokens broken
out of a string is, in effect, an ordered enumeration of those tokens, so StringTokenizer implements the
Enumeration interface[4] (see page 617). StringTokenizer provides methods that are more
specifically typed than Enumeration, which you can use if you know you are working on a
StringTokenizer object. The StringTokenizer enumeration is effectively a snapshot because
String objects are read-only. For example, the following loop breaks a string into tokens separated by
spaces or commas:
[4] For historical reasons it implements Enumeration<Object>, not
Enumeration<String>.
String str = "Gone, and forgotten";
StringTokenizer tokens = new StringTokenizer(str, " ,");
while (tokens.hasMoreTokens())
System.out.println(tokens.nextToken());
By including the comma in the list of delimiter characters in the StringTokenizer constructor, the
tokenizer consumes commas along with spaces, leaving only the words of the string to be returned one at a
time. The output of this example is
Gone
and
forgotten