Java Reference
In-Depth Information
throw new InvalidUserInputException(" readString() failed. "
+ "Input data is not a string");
}
}
If either a word or a string is recognized, the token is stored as type String in the sval field of the
StreamTokenizer object.
Let's see if it works.
Try It Out - Formatted Keyboard Input
We can try out our FormattedInput class in a simple program that iterates round a loop a few times
to give you the opportunity to try out correct and incorrect input:
public class TestFormattedInput {
public static void main(String[] args) {
FormattedInput kb = new FormattedInput();
for (int i = 0; i < 5; i++) {
try {
System.out.print("Enter an integer: ");
System.out.println("Integer read: " + kb.readInt());
System.out.print("Enter a double value: ");
System.out.println("Double value read: " + kb.readDouble());
System.out.print("Enter a string: ");
System.out.println("String read: " + kb.readString());
} catch (InvalidUserInputException e) {
System.out.println("InvalidUserInputException thrown.\n"
+ e.getMessage());
}
}
}
}
It is best to run this example from the command line. Some Java IDEs are not terrific when it comes to
keyboard input. If you try a few wrong values, you should see our exception being thrown.
How It Works
This just repeats requests for input of each of the three types of value we have provided methods for,
over five iterations. Of course, after an exception of type InvalidUserInputException is thrown,
the loop will go straight to the start of the next iteration - if there is one.
This code isn't foolproof. Bits of an incorrect entry can be left in the stream to confuse subsequent input
and you can't enter floating-point values with exponents. However, it does work after a fashion and it's
best not to look a gift horse in the mouth.
Search WWH ::




Custom Search