Java Reference
In-Depth Information
new BufferedReader(
new
InputStreamReader(System.in)));
private int ttype; // Stores the token type code
}
Directory "TestFormattedInput"
The default constructor is quite satisfactory for this class, because the instance variable tokenizer is
already initialized. The readToken() method is there for use in the methods that read values of various
types. It makes the ttype value returned by nextToken() available directly, and saves having to repeat
the try and catch blocks in all the other methods.
All you need to add are the methods to read the data values that you want. Here is one way to read a
value of type int :
// Method to read an int value
public int readInt() {
for (int i = 0; i < 5; ++i) {
if (readToken() == StreamTokenizer.TT_NUMBER) {
return (int) tokenizer.nval; // Value is numeric, so return
as int
} else {
System.out.println("Incorrect input: " + tokenizer.sval
+ " Re-enter an integer");
continue; // Retry the read operation
}
}
System.out.println("Five failures reading an int value"
+ " - program terminated");
System.exit(1); // End the program
return 0;
}
Directory "TestFormattedInput"
This method gives the user five chances to enter a valid input value before terminating the program. Ter-
minating the program is likely to be inconvenient to say the least in many circumstances. If you instead
make the method throw an exception in the case of failure here, and let the calling method decide what
to do, this would be a much better way of signaling that the right kind of data could not be found.
You can define your own exception class for this. Let's define it as the type InvalidUserInputExcep-
tion :
public class InvalidUserInputException extends Exception {
public InvalidUserInputException() {}
Search WWH ::




Custom Search