Java Reference
In-Depth Information
5.9.1
Reading the keyboard
Unless your program is expecting input and contains instructions to read what
you type, your program will not respond to typing. Fixing your program to read
from the keyboard requires several steps, the first of which is to link to the key-
board.
Activities
5-7.1, 5-7.2
Linking to the keyboard
Variable
System.in
, of type
InputStream
, represents
standard input
.
Standard input is usually the keyboard (although it can be set to some other input
source). So, we can view variable
System.in
as containing the name of an object
that
is
the keyboard.
System.in
is a stream of information, and it needs a
reader
to read from it.
For this purpose, we use an instance of class
InputStreamReader
. To create an
InputStreamReader
that is attached to the keyboard, use this statement:
This material is
much easier to
grasp from
activities 5-7.1
and 5-7.2!
InputStreamReader isr=
new
InputStreamReader(System.in);
Variable
isr
then contains the name of the instance that is attached to the key-
board, and its function
isr.read()
can be used to read from the keyboard. But
this function reads only one character at a time, and this can be slow and incon-
venient. Java provides a class
BufferedReader
that
buffers
the input: it reads
lots of characters at one time, saves them, and delivers them one line at a time.
To create a
BufferedReader
that reads from object
isr
, use this statement:
BufferedReader br=
new
BufferedReader(isr);
Variable
br
is now linked to the keyboard, and its function
br.readLine
can
be used to read the next line from the keyboard, e.g.
String s= br.readLine();
Evaluation of
br.readLine()
pauses until the user has typed the return/enter
key on the keyboard; then, it yields the string consisting of all characters that
were typed before the return/enter key was struck.
Handling IO errors
When reading input, problems may occur. The keyboard might get un-
plugged or break, something might go wrong inside your computer, etc. These
events cause
exceptions
, and Java forces you to deal with them.
We illustrate this using the procedure shown in Fig. 5.5. It will not compile
because the expression
br.readLine()
may cause an input-output exception to
happen (to be thrown). The syntax error message that is printed is:
Activity
5-7.3
Error: unreported exception
java.io.IOException
; must be
caught or declared to be thrown.
To make the procedure syntactically legal, remove the comment symbols
Search WWH ::
Custom Search