Java Reference
In-Depth Information
Using StringEnumeration in a procedure to print characters of a String
Now that we have class StringEnumeration , we write a procedure that
uses it to print the characters of a String :
/** Print the chars of s */
public static void print(String s) {
StringEnumeration e= new StringEnumeration(s);
while (e.hasMoreElements())
{ System.out.println(e.nextElement()); }
First, the procedure body creates an instance of class StringEnumeration
for s and stores it in local variable e . Next, a loop processes the characters of s ,
using e to enumerate the characters, one by one. The loop terminates when e
indicates that there are no more elements. Each loop iteration retrieves the next
element of e and prints it. This loop is so simple that we omit the invariant.
Pay attention to the way Enumeration e is used. Function nextElement
should be called only if it is known that there is another element to process, and
the only way to know that is to call hasMoreElements . Function hasMoreEle-
ments may actually be called several times in a row, but each call of function
nextElement must be preceded by a call to hasMoreElements because that is
the only way to determine whether there is another element to enumerate.
Casting the result of function nextElement
By definition, the result of function nextElement has type Object . In
method print above, we could use the fact that Object has function toString
defined on it in order to print each character in turn. However, it may be neces-
sary to cast the object back to Character in order to suitably process it. To illus-
trate this, in Fig. 12.8 we write a method that constructs a String that consists
of every other character of its parameter.
Get a class
with the
method of Fig.
12.9 from les-
son page 12.4.
/** = the string consisting of the first, third, fifth, …, chars of s */
public static String getAlternateCharacters(String s) {
String res= "";
StringEnumeration e= new StringEnumeration(s);
// inv: res contains the alternate chars of the part of s that has been enumerated, and
// an even number of characters has been enumerated
while (e.hasMoreElements()) {
res= res + (Character) (e.nextElement());
if (e.hasMoreElements()) {
Object throwAway= e.nextElement();
return res;
Program 12.8:
Function getAlternateCharacters
Search WWH ::

Custom Search