Java Reference
In-Depth Information
If you need a method to read an integer value and return it as one of the other integer types,
byte
,
short
,
or
long
, you could implement it in the same way but just cast the value in
nval
to the appropriate type. You
might want to add checks that the original value was an integer, and maybe that it was not out of range for
the shorter integer types. For instance, to do this for type
int
, we could code it as:
public int readInt() throws InvalidUserInputException {
if (readToken() != tokenizer.TT
_
NUMBER) {
throw new InvalidUserInputException(" readInt() failed. "
+ "Input data not numeric");
}
if (tokenizer.nval > (double) Integer.MAX
_
VALUE
|| tokenizer.nval < (double) Integer.MIN
_
VALUE) {
throw new InvalidUserInputException(" readInt() failed. "
+ "Input outside int range");
}
if (tokenizer.nval != (double) (int) tokenizer.nval) {
throw new InvalidUserInputException(" readInt() failed. "
+ "Input not an integer");
}
return (int) tokenizer.nval;
}
The
Integer
class makes the maximum and minimum values of type
int
available in the public
members
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, we cast it to an
integer, then cast it back to
double
and see whether it is the same value.
To implement
readDouble()
, the code is very simple. You don't need the cast for the value in
nval
since it is type
double
anyway:
public double readDouble() throws InvalidUserInputException {
if (readToken() != tokenizer.TT
_
NUMBER) {
throw new InvalidUserInputException(" readDouble() failed. "
+ "Input data not numeric");
}
return tokenizer.nval;
}
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() == tokenizer.TT
_
WORD || ttype == '\"'
|| ttype == '\'') {
return tokenizer.sval;
} else {