Input and output
Input to and output from the computer comes in the form of data streams. For human readable input and output these are streams of characters.
Unix defines three such standard streams :-
In Java, access to these streams is possible by reference to the three objects in the class System.
I/O exceptions
Input and output to a program can cause unexpected - or exceptional - events to occur from time to time. In Java, these exceptional events are called Exceptions. Exceptions can be dealt with within the program code - called exception handling, or simplyignored.
In an exception occurs at run-time and there is no provision in the code to handle it, the program will crash.
For the moment we will be content for this to happen on the understanding that such events are fairly unlikely.
Ignoring exceptions in Java
Exceptions in Java come in two different groups - one group can be completely ignored by the programmer if so desired, the other group cannot.
Unfortunately, IOExceptions come in this latter group. This means that any piece of code - method - which could give rise to an exception must either handle it or declare that it is not going to do so.
If it declares that it is not going to handle the exception, any method which calls this method must similarly either handle the exception or declare that it isn't going to.
The way that a method (e.g. main) would indicate that it isn't going to handle IOExceptions is to include a throws clause in it header, e.g. :-
import java.io.*; //this gives access to the resources to handle I/O
public class Demo {
public static void main(String [] args) throws IOException {
...
} //end main
} //end class Demo
Notice the class definition is preceeded with an import statement.This makes the I/O resources of Java available to the program and should be placed at the start of every program file that uses I/O.
Getting keyboard input
In order to get input into a program from stdin, it is necessary to create a reader object to read from the input stream and deliver the data to the program. This is done with the following piece of code which you should use on all occasions :-
import java.io.*;
public class Demo {
public static void main(String [] args) throws IOException {
String text; //variable to hold input data
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(reader);
text = stdin.readLine(); //reads a line of text from the keyboard
//and places it in variable - text
} //end main
} //end class Demo
In this example the first line declare a String variable capable of referring to some input data. The next two lines create a buffered reader on the inputstream. It is not important that you understand these lines at present - simply use them.
The last line input a line of text (terminated with carriage return) from the keyboard.
Inputting numbers
The above program allows us to input single characters or character strings from the keyboard, but we will also need to input numeric data.
Recall how this was done with command line arguments. These are simply strings which can be converted to numeric values by use of the methodInteger.parseInt(). There is a similar method for convertingStrings to doubles - Double.parseDouble().
To illustrate this, the following program prompts for name, age and height and displays the result.
import java.io.*;
public class Demo {
public static void main(String [] args) throws IOException {
String name; //variable to hold input name
String text; //variable to hold input number before conversion
int age; //integer age
double height; //double height
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(reader);
System.out.print("Enter your name ");
name = stdin.readLine();
System.out.print("Enter your age :");
text = stdin.readLine(); //get age as a string
age = Integer.parseInt(text); //convert it to integer
System.out.print("Enter your height to 2 dec places");
height = Double.parseDouble(stdin.readLine()); //note - you can combine the input
//and conversion into one statement
} //end main
} //end class Demo
Dealing with errors
You might wonder what happens when something other than a number is entered when one is expected. The Integer.parseInt() method for conversion of a string to an int and the Double.parseDouble() method for converting a string to a double both raise an exception - NumberFormatException. So by catching and handling this exception, corrective action or error diagnostics can be produced without the program crashing.
For instance, the following piece of code requests an integer value from the keyboard and if something else is typed it issues an error message and prompts again :-
String text; //variable holds number before conversion
int age; //integer age
boolean ok = false; //indicates valid input received
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(reader);
while (!ok){
try {
System.out.print("Enter a number ");
text = stdin.readLine(); //get number as string
age = Integer.parseInt(text); //attempt conversion
ok = true; //if we get here all is ok
} //end try
catch(NumberFormatException nfe){
System.err.println("Input not a number");
} //end catch
} //end while