Fundamentals of Computer Science II (CSC-152 97F)
Outline of Class 15: Program Input
- Program input in Java is somewhat more complicated than output.
- There is a
System.in object for the standard input
to a program, corresponding to the
for standard output.
System.in is a member of
- Unfortunately, you cannot directly access
- Why? Because there are typically a number of things that you want
to do with input.
- You may want to buffer the input (group a sequence
of characters into a larger array). This generally speeds up
the program and, more importantly, lets you "unread" elements
- You may want to specify the encoding used in the input.
- In Java 1.0, you must construct a
the input stream.
- This can help generalize your code, as you can quickly
change a program from reading standard input to reading
a file by building a
the file, rather than standard input.
DataInputStream provides much more useful and
usable methods than
InputStream. However, these
methods are generally only appropriate for non-character data
and assume that you've written the data using a
- The safest thing to use is
but that will require you to do a lot of work converting to
- These methods all throw IOExceptions, so you may need to
- There is no explicit end-of-file test. Rather, an
EOFException is thrown when you try to read
beyond the end of the file.
DataInputStream and its associated exceptions are not
automatically part of your program. You must import them. It is
easiest to do so with
- Java 1.1 introduced
Reader (and, more importantly,
- To get an object from which you can read lines, you would
new BufferedReader(new InputStreamReader(System.in));
readLine() method does not seem to throw
- Because Java-style I/O is such a pain, the author of our textbook has
provided a nice interface through the
- You can find information on this class at
- Basically, you construct a new member of that class, and then you can
do fun things like
- reading individual characters with
- reading whole lines with
- reading integers with
- checking end of file with
- Write a program that reads a series of integers from standard input
(one per line),
and reports on the maximum, minimum, and average.
- If you have time, make sure that your program doesn't crash if
incorrect input is given.
- If you have time and inclination, extend your program to compute the median.
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Tue Oct 7 17:12:39 1997.
This page generated on Wed Nov 5 12:38:41 1997 by SiteWeaver.
Contact our webmaster at firstname.lastname@example.org