Input and Output
To be useful,
a program must input data and output the results of processing
that data.
This chapter discusses some easy ways to input and output
data from the keyboard and monitor.
Input and output operations are a very complicated aspect
of computers (and computer programming languages),
so this chapter is just a beginning.
- Input and Output Streams.
- The standard IO streams.
- Exceptions
- InputStreamReader and BufferedReader Classes.
- Converting character data to type int.
Note: If you are reading a Java textbook
and are also following these notes you may find that
your text book uses its own methods for doing input from
the keyboard.
This is OK,
You can still use these notes.
The methods used in these notes are part of the
JDK (Java Development Kit)
and will work for every Java installation.
The methods in your textbook are (probably) unique to that book
and require you to use a special package written by the book's author.
Those methods are based on the methods in the JDK and are fundamentally
the same as the methods used in these notes.
No Built-in IO
Input and output are so common that an abbreviation has
been created for them: IO (pronounced eye-oh.)
IO operations are very complicated, both at the software level
and at the electronic level.
Part of the problem is that the way in which data is organized
outside the computer is different from the way it
is organized inside the computer.
There are no standard statements in the Java language for doing input or output.
All input and output is done by using methods that are part of a
package.
A package is a collection of classes
which may be used with other programs.
For now, think of a package as a tool box
and the classes within it as tools.
Several IO packages are available.
Usually a programmer picks just one of them,
whichever contains the classes needed for the job.
These notes use the java.io package,
which is the IO package used most often.
It may seem odd to you
that Java itself does not have IO built into it.
The reason for this is that there are very many types of IO,
and a language that has all of them built in would be large and
cumbersome.
A professional language such as Java (or C or C++ or any of several others)
allows the programmer to pick the right IO package for the job.
Note: As mentioned, some text books use
their own IO package
based on java.io.
Those methods will be somewhat different from those
described here, but the ideas are the same.
IO Streams
If the car's computer program were written in Java,
it would use
a specialized IO package
that manages sensors and controllers.
It would
not use the IO package that deals with keyboards and terminals.
In Java, a source of input data is called an input stream
and the output data is called an output stream.
Think of these streams like this:
In this picture, each "O" is supposed to be a datum (chunk of data)
waiting in line to be input, or leaving as output.
Inputting data is usually called reading data;
and outputting data is usually called writing data
(or printing data if the output stream is connected to
a monitor or a printer.)
You might think of the input stream as a string of pearls which the
program inputs one at a time, in order.
The output stream is a string of new pearls (not usually the same ones
as came in.)
Often a program will have to input several data in a row before it has
enough to process.
For example,
the input data might be a list of numbers,
the output data might be their sum.
In general, a program may have several input streams flowing into it and several
output streams flowing out of it.
For most of the programs in these notes, there are three IO streams:
- System.in the input stream.
- System.out the output stream for normal results.
- System.err the output stream for error messages.
Normally System.in is connected to the keyboard
and the data are characters.
System.out and System.err both are connected
to the monitor, and
also are character data.
These streams are difficult to manage by themselves.
We will use the package java.io to help.
Characters In, Characters Out
The data a keyboard sends to
a program is character data,
even when the characters include the digits '0' through '9'.
If your program does arithmetic,
the input characters
will be converted into one of the primitive numeric types.
Then the result is calculated (using arithmetic),
and then the result is converted to character data.
The information a program sends to the monitor is character data:
(Actually, the characters are not really sent directly to the monitor.
They, along with everything else the monitor displays,
are first converted into a video signal by a graphics card.
This business of converting data from one form to another is
very common in computers.)
- Yes,
System.out.println("Some string" + 123)
sends characters to the ouput stream.
- Did it have to convert a primitive numeric type to character data?
- Yes,
"Some string" + 123 converts the integer
123 from a primitive numeric type into characters
that are appended to "Some string".
Example IO Program
The following program reads characters from the keyboard into
the String called inData.
Then the characters stored in that String are sent to the monitor.
The details of this program are explained in the next several pages.
import java.io.*;
class Echo
{
public static void main (String[] args) throws IOException
{
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
String inData;
System.out.println("Enter the data:");
inData = stdin.readLine();
System.out.println("You entered:" + inData );
}
}
The line import java.io.*; says that the package java.io
will be used.
The * means that any class inside the package might be used.
Here is how this program runs:
C:\users\default>java Echo
Enter the data:
This is what the user enters
You entered:This is what the user enters
Main Method
Later on we will do something special to convert strings of digits
into primitive numeric types.
This program does not do that.
Here is the program again:
import java.io.*;
class Echo
{
public static void main (String[] args) throws IOException
{
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
String inData;
System.out.println("Enter the data:");
inData = stdin.readLine();
System.out.println("You entered:" + inData );
}
}
The main method of class Echo starts with the line:
public static void main (String[] args) throws IOException
You have seen most of this line before.
This part: throws IOException is necessary for programs that do
input (at least for now.)
It informs the compiler
that main() does an input operation that might fail.
When the program is running and an input operation fails,
the computer system will be informed of the failure and the
program will be gracefully halted.
It would be extremely useful if you played with this program using
the copy-paste-and-run method.
Exceptions
On 1950's mainframes and even many 1990's PCs
a single input mistake could cause the entire computer system
to stop dead (a "crash").
Programs were written with the unreasonable expectation that
all input data would be correct and would be read in successfully.
Java is an industrial-strength programming language,
and is designed to help the programmer
deal with bad data and the all-too-common input failures.
When an input or an output operation fails,
an exception is generated.
An exception is an object (a chunk of main memory) that contains
information about what went wrong.
The section of code where the problem occurred can deal with the
problem itself,
or pass the exception on.
Passing the exception on is called throwing an exception.
The phrase throws IOException in:
public static void main (String[] args) throws IOException
. . .means that the part of the system that started main() must be
prepared to deal with an IO exception.
For us,
all this means is that the program will be halted gracefully.
Java has been proposed as the language for writing airplane
traffic control programs.
If an IOException occurred in one of those programs,
would you expect the system to merely halt gracefully?
BufferedReader
In many real-world programs, the program must keep running no matter what.
The program must deal with an
exception by fixing the problem or working around it.
Java is designed for such programs.
Here is the example program again.
Look at the first two statements in the main method.
import java.io.*;
class Echo
{
public static void main (String[] args) throws IOException
{
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
String inData;
System.out.println("Enter the data:");
inData = stdin.readLine();
System.out.println("You entered:" + inData );
}
}
These statements may look somewhat mysterious.
It is a bit too early to explain all their details.
For now, just think of them as something messy you do to
create a BufferedReader
object that does input from the keyboard.
The object will be called stdin.
You can think of the two statements as a fill-in-the-blank form.
Fill in the blank with the name you want for the BufferedReader:
InputStreamReader inStream =
new InputStreamReader( System.in );
BufferedReader ___________ =
new BufferedReader( inStream );
Details (if you want them)
Here are some details of what is going on.
Skip this page and the next if you want.
Look at the two statements:
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
The first statement declares the variable inStream.
It has the form you have seen before:
typeName variableName = initialValue ;
Here the typeName is InputStreamReader,
a class that is part of the java.io package.
You know this is a class,
because the type is not one of the eight primitive types.
The variable inStream is an object of that data type.
onClick="alert('The data type of an object is called its class.')">
In the first statement, the initialValue will be an object.
The new operator constructs an object of the requested type.
Once the object is constructed (out of main memory) it can be referred to
by the variable inStream.
(There will be much more on this later in these notes.)
More Details
An InputStreamReader object reads data from some source
(such as System.in).
However, it is awkward to use by itself.
A BufferedReader object is easier to use,
but needs to be connected to an InputStreamReader.
Look at these two lines from the program:
InputStreamReader inStream =
new InputStreamReader( System.in ) ;
BufferedReader stdin =
new BufferedReader( inStream );
The first line constructs an InputStreamReader object and
gives it the name inStream.
The second line constructs a BufferedReader object
and connects it to inStream.
The BufferedReader is called stdin.
To create a BufferedReader
the new operator is used:
BufferedReader stdin = new BufferedReader( inStream );
The new operator
creates a BufferedReader object out of main memory.
The BufferedReader object can then be used to do input.
"BufferedReader" appears twice in this statement
because the first "BufferedReader" describes the type of the variable stdin,
while the second one tells the new opeator what type of object to create.
Assembly Line
The BufferedReader object uses
the InputStreamReader object as its connection
to System.in.
This connection is made when the BufferedReader is constructed:
BufferedReader stdin =
new BufferedReader(inStream );
Think of this as an assembly line: System.in gets characters from the
keyboard.
The InputStreamReader reads the characters
from System.in and hands them to the BufferedReader.
The BufferedReader objects hands the data to your program when
requested.
Looking at the picture you see why this is called an "input stream".
Data streams in from the keyboard through several processing stages
before it gets to your program.
You don't have to memorize and completely understand all of this right now.
It is confusing.
In fact, it is here that many text books use their own simpler input methods
(which usually does little more than hide what is going on).
One-line Version
Once the connection is made, the variable is not used again.
In fact, you don't need to use it at all because the connection
can be made all in one line:
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
If you want,
you can think of this
one very long command that means "get ready to read stuff in."
The complete program is now:
import java.io.*;
class Echo
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
String inData;
System.out.println("Enter the data:");
inData = stdin.readLine();
System.out.println("You entered:" + inData );
}
}
This one statement takes up two lines.
This is OK. Statements end with a semicolon, not at the end of a line.
Use indenting to show when a long statement has been written on two
(or more) lines.
readLine()
The program reads a line of character data from the
keyboard by using the method readLine(),
which is part of the BufferedReader object.
inData = stdin.readLine();
It gets a line of characters,
and assign them to the String
inData.
Then the next statement
System.out.println("You entered:" + inData );
writes the string to the monitor.
Here is what a run of the program looks like:
Enter the data:
To learn Java, you must play with the programs!
You entered:To learn Java, you must play with the programs!
When you run the program you can correct
what you type using the "delete" key and "backspace" key.
Only when you hit "enter" are the characters
sent to your program.
Numeric Input
Here is another run of the program:
Enter the data:
Columbus sailed in 1492.
You entered:Columbus sailed in 1492.
Notice that the characters '1', '4', '9', and '2' were read in and
written out just as were the other characters.
Now consider yet another run:
Enter the data:
1492
You entered:1492
Nothing special here.
The '1', '4', '9', and '2' are still characters.
If you want the user to enter numeric data,
your program must convert from character data to a numeric type.
The characters are first read into a String object.
Then the String object is converted into a numeric type.
This is done using a wrapper class.
Integer Input
(It would not be too surprising if you forgot that.)
Here is a program that computes the square of
a number that the user enters.
It uses the one-line method of constructing
a BufferedReader.
import java.io.*;
class EchoSquare
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader (new InputStreamReader(System.in));
String inData;
int num, square; // declare two int variables
System.out.println("Enter an integer:");
inData = stdin.readLine();
num = Integer.parseInt( inData ); // convert inData to int
square = num * num ; // compute the square
System.out.println("The square of " + inData + " is " + square);
}
}
This program is the previous program
with a few additions
(in blue).
You can copy-paste-and-run it.
Better yet,
study it for a while,
then go to NotePad and see how much
you can reconstruct.
Now look at this statement:
num = Integer.parseInt( inData ); // convert inData to int
This uses the method parseInt() of the Integer wrapper class.
This method takes a String containing an integer in
character form.
It looks at those characters and calculates
an int value.
That value is assigned to num.
Converting to Integers
Here is the line from the program, again:
num = Integer.parseInt( inData ); // convert inData to int
Assignment statements work in two steps:
- Evaluate the expression on the right of the equal sign,
- Put the value in whatever variable is on the left.
In this particular statement, the expression on the right
evaluates to an int value by using a method call.
Then in the second step that value is assigned to the variable.
This process is usually called converting the characters
to an integer.
Caution: The string inData is not changed at all.
It is "converted" only in the sense that an integer value is
calculated based on its contents.
NumberFormatException
If the user enters one of the WRONG lines,
the statement
inData = stdin.readLine()
will work without any problem.
It will read in the characters the user typed and put them in
the String object inData.
However, the method
parseInt in the statement
num = Integer.parseInt( inData )
will not be able to understand the characters as an integer,
and with throw an exception.
The user will see something like:
Enter an integer:
14.92
java.lang.NumberFormatException: 14.92
This exception was passed out of the running program to the Java system,
which stopped the program and wrote the error message.
The parseInt method is just one method of the wrapper class Integer.
It should be used like this:
intVariable = Integer.parseInt( stringVariable );
The stringVariable should contain only characters that can
be interpreted as an integer.
Could the following be interpreted as an
integer?
" 84"
Notice that there are two spaces preceeding the '8' character.
Another Example
Here is another example, suitable for "copy-paste-and-run."
It asks the user for two integers which are to be added together.
import java.io.*;
class AddTwo
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String line1, line2; // declaration of input Strings
int first, second, sum ; // declaration of int variables
System.out.println("Enter first integer:");
line1 = stdin.readLine();
first = Integer.parseInt( line1 ); // convert line1 to first int
System.out.println("Enter second integer:");
line2 = stdin.readLine();
second = Integer.parseInt( line2 ); // convert line2 to second int
sum= first + second;// add the two ints, put result in sum
System.out.println("The sum of " +
first + " plus " + second +" is " + sum );
}
}
Study the program for a while. Notice how the indenting and blank lines
help in displaying how the program is organized.
Here is a sample run of the program:
Enter first integer:
12
Enter second integer:
-8
The sum of 12 plus -8 is 4
Integer Division Tester
Remember that when Java sees + next to a String,
it tries to make an even longer string.
In this version of the last statement, the Strings line1
and line2 are concatenated to output String.
No conversion needs to be done.
Then,
the int sum is converted to a String,
and concatenated to the end.
Here is a new program made by modifying the first program.
- The user enters two integers,
dividend and divisor.
- The program calculates and prints the
quotient and the remainder.
- The program calculates and prints
quotient * divisor + remainder.
import java.io.*;
class IntDivideTest
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String top, bottom; // input Strings
int dividend, divisor ; // int versions of input
int quotient, remainder ; // results of "/" and "%"
System.out.println("Enter the dividend:"); // read the dividend
top= stdin.readLine();
dividend = Integer.parseInt( top );
System.out.println("Enter the divisor:"); // read the divisor
bottom = stdin.readLine();
divisor = Integer.parseInt( bottom );
quotient = dividend / divisor ;// perform int math
remainder= dividend % divisor ;
System.out.println( dividend + " / " + divisor + " is " + quotient );
System.out.println( dividend + " % " + divisor + " is " + remainder );
System.out.println( quotient + " * " + divisor +
" + " + remainder + " is " + (quotient*divisor+remainder) );
}
}
Run the program a few times. See what happens when negative
integers are input.
IF MY ARTICLE IS GOOD AND YOU CAN UNDERSTAND PLEASE VOTE ME .
|