Java Reference
In-Depth Information
Here we read the first name followed by the surname as two separate strings, and then create the
Person
object that is returned. If a
!
character was entered instead of a first name,
null
is returned by
the
readPerson()
method signaling the end of the input. Since this method uses the
FormattedInput
class that we defined in Chapter 8, you need to copy the file containing the
definition of this class to the same directory as the
TryVector
class. The
readString()
method that
we defined in the
FormattedInput
class doesn't quite do what we want though. We could insist that
the
!
character to end the input is entered between quotes. However, it's not a very natural way to enter
the data. If we could get a single character that is not alphanumeric back as a string, then that would fix
the problem for us. A small tweak of the
readString()
method in the
FormattedInput
class will
accommodate that:
public String readString() {
if(readToken()==tokenizer.TT
_
WORD || ttype == '\"' || ttype == '\'')
return tokenizer.sval;
else
return String.valueOf((char)ttype);
}
You will recall that if you enter a string delimited by quotes, the quote character that you use is returned
by the
nextToken()
method. If a character string is entered without quotes, then
TT
_
WORD
is
returned. Thus the first
if
expression will be
true
if either of these is the case, so we return the string
stored in
sval
. Of course, this will not include the double quote characters if they are present.
Programming the method like this provides for quoted and unquoted strings, so we can enter names that
contain spaces by putting them between quotes.
When a
!
is entered, it is returned by the
nextToken()
method, so in this case we return a string
containing just this character to signal to the calling program that this is the end of the input. You could use
any non-alphanumeric character for this. Note that
ttype
is of type
int
so we can't pass its value directly to
the
valueOf()
method. If we did, we would get the string representation of its numerical value.
If you've swapped this version of the method into the
FormattedInput
class, and placed the source
files for the other classes in the same directory, you should be ready to give it a whirl. With a modest
film budget, I got the output (my input is in bold):
Enter first name or ! to end:
Roy
Enter surname:
Rogers
Enter first name or ! to end:
Marilyn
Enter surname:
Monroe
Enter first name or ! to end:
Robert
Enter surname:
"
de Niro"