Java Reference
In-Depth Information
that delimit the
throws clause
Throws
IOException
in the header of the method.
This signals that this method may throw an
IOException
. Now, this method is
syntactically correct, but the method that called this one may be syntactically
incorrect and will also need a throws clause, and so on.
The upshot of this is that if the statement
br.readLine()
causes an
IOException
, the system will print an error message and terminate execution of
the program.
For a complete discussion of handling exceptions, see Chap. 10.
Extracting numbers
Assume that a line
"-77"
of keyboard input has been placed in
String
vari-
able
line
and that our task is to extract the integer from
line
and place it in
int
variable
i
. Static function
parseInt
of wrapper class
Integer
will do the job:
execution of:
Activity
5-7.4
i= Integer.parseInt(line);
converts the string in variable
line
to an integer and stores the integer in vari-
able
i
.
The two statements to read in a line of keyboard input and extract the inte-
ger in it can be combined to avoid declaring the unnecessary variable
line
:
i= Integer.parseInt(br.readLine());
But there is a problem with function
parseInt
: it does not allow white-
space, like blank characters, to appear before or after the integer. Thus, evalua-
tion of this expression results in an error message and abortion of the program:
Integer.parseInt(" 35 ")
Remove the whitespace from the input using
String
function
trim
:
Integer.parseInt(" 35 ".trim())
Thus, we should read a line containing an integer, possibly with preceding
/**
Read and print two lines from the keyboard. As written, it does not compile. Remove
the comment delimiters around the throws clause on the first line and it will compile.
*/
public static void
readAndProcess () /* throws IOException*/ {
InputStreamReader isr=
new
InputStreamReader(System.in);
BufferedReader br=
new
BufferedReader(isr);
String line1= br.readLine();
System.out.println(line1);
String line2= br.readLine();
System.out.println(line2);
}
Figure 5.5:
A procedure to read and print two lines from the keyboard
Search WWH ::
Custom Search