LEC 11 3. Interactive Input-Output
LEC 11 3. Interactive Input-Output
Pilani Campus
To extract data that is at a “higher level” than the byte, we must “encase” the
InputStream, System.in, inside an InputStreamReader object that converts
byte data into 16-bit character values (returned as an int).
BufferedReader
InputStreamReader
import java.io.*;
public class TotalNumbers throws java.io.IOException{
private String str;
private int num;
public static void main (String [] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print(“Enter four integers: “);
str = br.readLine( );
str = 6 2 4 3 2 1
str = 6 2 4 3 2 1
Unlike primitive types, objects have operations called methods that they can
be directed to perform. (These methods have visibility static they can be
accessed by using the class name without instantiating objects of the class.
Wrapper class objects have a method for converting a string into a primitive
type, and a method for transforming a primitive type into a string.
wrapper method name return type
Integer parseInt(String st) int
Integer toString(int num) String
Double parseDouble(String st) double
Double toString(double num) String
Float parseFloat(String st) float
Long parseLong(String st) long
Return to the code for extracting tokens from the input string
Step 3 – Form input stream of characters into a string (look for eol)
BufferedReader br = new BufferedReader(isr);
String str = br.readLine( ); Need to throw java.io.IOException in function in
which it is used
String s1 = st.nextToken( );
//note can use while(st.hasMoreTokens( )) to repeatedly extract each
//token in the string
Step 6 – Use wrapper class methods to convert token (string) to primitive type
the message
?
OK Cancel
WARNING_MESSAGE !
QUESTION_MESSAGE ?
INFORMATION_MESSAGE
ERROR_MESSAGE
PLAIN_MESSAGE
produces
greetings X
Little Programmers!
OK
JOptionPane.PLAIN_MESSAGE
The icon_type determines which of the five icons (the fifth being no
icon at all) will appear in the dialog box.
1. import javax.swing.*;
2. Use an input dialog box to prompt the user to enter data (returns a String)
String inString = JOptionPane.showInputDialog(“your message”);
3. Use a StringTokenizer (if necessary) to extract the individual tokens
from the input String
4. Convert (String) tokens into primitive types wherever necessary using
the appropriate wrapper class.
5. Use a dialog box to display the output
JOptionPane.showMessageDialog(null,”message”, “title”, icon-type):
6. When using a Message dialog box, end the program with
System.exit(0);