Java Reference
In-Depth Information
Let's see if it works.
TRY IT OUT: Formatted Keyboard Input
You can try out the 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());
}
}
}
}
Directory "TestFormattedInput"
It is best to run this example from the command line. Some Java development environments are not ter-
rific when it comes to keyboard input. If you try a few wrong values, you should see your exception
being thrown.
How It Works
This just repeats requests for input of each of the three types of value you have provided methods for,
over five iterations. Of course, after an exception of type InvalidUserInputException is thrown, the
loop goes 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.
Writing to the Command Line
Up to now, you have made extensive use of the println() method from the PrintStream class in
your examples to output formatted information to the screen. The out object in the expression Sys-
Search WWH ::




Custom Search