Java Reference
In-Depth Information
However, we advise against the use of the methods because using them may lead
to errors. We explain.
Suppose the user types a line shown above in a situation where the program
is expecting three int s. The user has made a mistake, since 4.0 is not an int .
Upon trying to read 4.0, function readInt prints an error message and asks the
reader to type the integer again, this time correctly. But then the rest of the line,
containing the integer 3, will probably be discarded along with the 4.0, and most
of what the user typed is thrown away and has to be typed again. It may be dif-
ficult for the user to remember what has to be typed and what does not.
Thus, allowing several items to be typed on one keyboard line makes recov-
ery from a typing error much more difficult, and, as we all know, it is easy to
make errors while typing. Thus, it is better to stick to the one-item-on-a-line
mode when dealing with keyboard input.
Self-review exercises
SR1 . Open class JLiveRead in DrJava and compile it. Then type the following
expressions into the Interaction pane and evaluate them. During evaluation, a
box will appear into which you should type an appropriate value. Experiment
with making errors when typing values to see what happens.
JLiveRead.readLineInt()
JLiveRead.readLineBoolean()
JLiveRead.readLineNonwhiteChar()
JLiveRead.readLineString()
JLiveRead.readString()
SR2 . Write and test a procedure to read two integers from the keyboard and print
their product.
SR3 . Write and test a function to read two boolean values from the keyboard
This instance of the GUI has four int fields and the
ready button. Two integers were typed in the first two
fields and the ready button was pressed, causing the
sum of the two integers to be displayed in the third
int field.
The GUI can have up to 7 int fields, 7 double
fields, and 7 String fields. When the ready button is
pressed, method buttonPressed is called. You can
change this method to do whatever you want.
Figure 5.4:
GUI JLiveWindow
Search WWH ::




Custom Search