Java Reference
In-Depth Information
+ "Input not an integer");
}
return (int) tokenizer.nval;
}
Directory "TestFormattedInput"
The
Integer
class makes the maximum and minimum values of type
int
available in the public mem-
bers
MAX_VALUE
and
MIN_VALUE
. Other classes corresponding to the basic numeric types provide similar
fields. To determine whether the value in
nval
is really a whole number, you cast it to an integer and then
cast it back to
double
and see whether it is the same value.
The code to implement
readDouble()
is very simple. You don't need the cast for the value in
nval
be-
cause it is type
double
anyway:
public double readDouble() throws InvalidUserInputException {
if (readToken() != StreamTokenizer.TT_NUMBER) {
throw new InvalidUserInputException("readDouble() failed."
+ "Input data not numeric");
}
return tokenizer.nval;
}
Directory "TestFormattedInput"
A
readFloat()
method would just need to cast
nval
to type
float
.
Reading a string is slightly more involved. You could allow input strings to be quoted or unquoted as
long as they were alphanumeric and did not contain whitespace characters. Here's how the method might
be coded to allow that:
public String readString() throws InvalidUserInputException {
if (readToken() == StreamTokenizer.TT_WORD || ttype == '\"'
|| ttype == '\"') {
return tokenizer.sval;
} else {
throw new InvalidUserInputException("readString() failed."
+ "Input data is not a
string");
}
}
Directory "TestFormattedInput"
If either a word or a string is recognized, the token is stored as type
String
in the
sval
field of the
StreamTokenizer
object.