Sei sulla pagina 1di 5

Input and Output in Java There are no standard statements in Java for input and output.

All input and output is done using methods in a number of standard Java classes. These classes are found in a number of Java packages, however the most common Java package is java.io. Several IO packages are available, and a programmer can choose the one that contains the required classes. The most common IO package is the package java.io.

IO Streams
A stream is a sequence of characters or bytes used for program input or output. In general there may be several input streams and output streams. Java provides many different input and output stream classes in the java.io API. The most commonly used IO objects are: System.in (input stream) System.out (output stream for normal results) System.err (output stream for error messages)

These objects are used to input data from the user into the application, and output data to the user. Generally System.in is connected to the keyboard and inputs character data*, and System.out and System.err are connected to the monitor and output character data. *The data collected by the System.in object is character data, even if they are entered as numeric digits. Therefore if the application performs any calculations, the input characters, it must first be converted to the primitive data type before it is used. The Standard Output Stream: System.out We have already used the standard output stream, System.out, which is declared in the System class and is associated with the console window. Writing characters to the System.out using method print() or println() displays these characters on your screen. Any character, printable or not can be read from or written to a stream. A stream has no fixed size, as we write information to a stream we are just adding characters to the end of the stream. The stream output methods keep track of the size of the stream. Example: For the statement System.out.println(Age is + age + \nName is + name); The string expression in parentheses is evaluated, and the characters are appended to the standard output stream. During the evaluation process, the

binary numbers stored in age is converted to a seqence of decimal digit System PrintStream out; other attributes

getData(); characters. setData(); other methods User Input using the Keyboard There are a number of ways to accept input from the user. We will look at three PrintStream attributes of them, 1. Buffered Reader 2. Scanner 3. JOptionPane Buffered Reader (java.io) print(); PrintStream

In the System class, there are objects println(); that can be used to accept and output data to the user. The object, System.in, represents the keyboard (unless you specify otherwise), and is used to read otherdata (entered using the keyboard) user methods into your program. The class BufferedReader reads data from standard input (System.in, the keyboard. It may look confusing, but it does this in two steps. Step 1: Create an InputStreamReader object InputStreamReader objects read characters from an input stream, in this case, the keyboard input stream, System.in. The constructor method of class InputStreamReader takes the input stream object as an argument. However objects from this class offer limited functionality because they read a single character at a time. When we read in data from the user, we do not want to have to process the data character by character, we want to read and process the characters as a whole. This is why the next step is necessary. Step 2: Create a BufferedReader object The class BufferedReader offers additional functionality. It has methods that allow us to read characters and lines of data more easily. We wrap our InputStreamReader object inside a BufferedReader object, to add on extra functions. The two step process looks like the one below:

InputStreamReader sysIn = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(sysIn); Step 3: Get input from user In the next step, we read the data from the user from the command line. The user enters data, followed by the return key, and the text that preceeded (came before) the return can be stored in our program. Generally, because we want to give some instruction to the user (i.e. enter something now) we will output an instruction, before we read the users data. System.out.println(Hey You, enter something!); String userInput = input.readLine(); After this, the String object reference now points to the user-entered data. In the example above, the method readLine() is a method that belongs to the BufferedReader class, that reads a line of text from the user. IMPORTANT: Data collected using the readLine() method is always CHARACTER data. Therefore, if we want to do some calculations with the data, we first have to convert the data to numeric data before we can process it. Step 4: Convert character data to numeric data (if required) We talked about type wrappers before. A type wrapper is a class that has methods we can use to convert objects such as String objects to primitive data types, such as int or double. To convert String data to int data, we use the wrapper class Integer (and Double for double etc). The class Integer has a method, parseInt() that we invoke on a String object and which returns an int result. int myData =Integer.parseInt(userInput); Now we are free to use myData in our application. Example: EchoSquare.java Exceptions Java is a programming language that is designed to help the programmer deal with bad data, and common input failures. An exception is an indication of a problem that occurs during a programs execution. The name exception implies that the problem occurs infrequently (i.e. exception to the rule). There are many situations that can cause an exception in a Java application. When an exception occurs, an exception object is created that contains information about what went wrong. Exception handling allows programmers to create applications that can resolve exceptions. There are two ways to deal with the exception; one is to write code to elegantly handle the exception, in the

section where an exception may occur. The second is to bypass the exception. This is called throwing an exception, and is required in cases where exceptions may occur. When you are throwing an exception, you are basically acknowledging that an error may occur, but that you wish to bypass the error. We will look at exception handling later in the course, and for now we will just throw exceptions. There are a number of types of exceptions. With input/output operations, when an operation fails, the application will generate an IOException. In order to tell the application to bypass or throw the error, we include the following code in our main method declaration. public static void main(String[] args) throws IOException {} In the previous statement, throws is a keyword that indicates we wish to throw an exception. IOException indicates that the exception generated will be related to input/output operations. Without the throw statement, when you compile your program, you would get the following compile time error: Error: unreported exception java.io.IOException; must be caught or declared to be thrown Scanner The Scanner class is a class in java.util, which allows the user to read values of various types. The Scanner class has many methods, but we will only use a few of them. We will first look at the ones that allow us to read in numeric values from either the keyboard without having to convert them from strings and determine if there are more values to be read. Useful Scanner methods are listed below: Method Returns nextInt() Next token as an integer nextDouble() Next token as a double next() Next token as a String nextLine() Returns the entire line (or remaining line) as a String. The Scanner object looks for tokens in the input. A token is a group of characters that are separated by whitespace (space, tab, line return, end of file). A token is a series of characters that ends with what Java calls whitespace. If we read a line that is a series of numbers, separated by blanks, the Scanner sees each number as a separate token. The numeric values may all be on one line with blanks between each value or may be on separate lines. Whitespace characters (blanks or carriage returns) act as separators. Example: ScannerExampleHere.java

JOptionPane

The JOptionPane class is part of the package javax.swing. This class contains methods for displaying input panes (dialog windows) which return user entered data and displaying output panes that output to program data. The common methods that we will use are shown in the table below. Method
showInputDialog(String message) showMessageDialog(Container parent, String message)

Returns
Displays input window and returns the String object entered by the user. Displays a message window that takes the user entered String as an argument and returns void.

For each of the methods, there are more than one constructor. The constructor that we invoke, and the arguments that we pass to the constructor determine the appearance of the window. Both methods are Class methods. This means that they belong to the class as a whole, rather than a specific instance of the class. We do not need to create a JOptionPane object in order to use the methods. To invoke the methods we use the class name. JOptionPane.showInputDialog(Your message here);

Example: JOptionPaneExampleHere.java

Potrebbero piacerti anche