Java Reference
In-Depth Information
All we need to add are the methods to read the data values that we 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() == tokenizer.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;
}
This method gives the user five chances to enter a valid input value before terminating the program.
Terminating the program is likely to be inconvenient to say the least in many circumstances. If we make
the method throw an exception in the case of failure here instead, 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.
We can define our own exception class for this. Let's define it as the type
InvalidUserInputException :
public class InvalidUserInputException extends Exception {
public InvalidUserInputException() {}
public InvalidUserInputException(String message) {
super(message);
}
}
We haven't had to add anything to the base class capability. We just need the ability to pass our own
message to the class. The significant thing we have added is our own exception type name.
Now we can change the code for the readInt() method so it works like this:
public int readInt() throws InvalidUserInputException {
if (readToken() != tokenizer.TT _ NUMBER) {
throw new InvalidUserInputException(" readInt() failed. "
+ "Input data not numeric");
}
return (int) tokenizer.nval;
}
Search WWH ::




Custom Search