0% found this document useful (0 votes)
6 views19 pages

LEC 11 3. Interactive Input-Output

Uploaded by

art3mis0906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

LEC 11 3. Interactive Input-Output

Uploaded by

art3mis0906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

BITS Pilani

Pilani Campus

Object Oriented Programming (CS F213)


Interactive Input/ Output
Contents

1. Reading data from the keyboard


2. Extracting separate data items from a String
3. Converting from a String to a primitive numerical type
4. An example showing how numerical data is read from
the keyboard and used to obtain and display a result
5. Using dialog boxes to obtain input data and display
results

BITS Pilani, Pilani Campus


Keyboard Input

The System class in java provides an InputStream object: System.in


And a buffered PrintStream object System.out

The PrintStream class (System.out) provides support for outputting


primitive data type values.
However, the InputStream class only provides methods for reading byte
values.

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).

We next “wrap” a BufferedReader object around the InputStreamReader to


enable us to use the methods read( ) which returns a char value and readLine( ),
which return a String.

BITS Pilani, Pilani Campus


Keyboard Input

BufferedReader
InputStreamReader

byte int string

import java.io.*; //for keyboard input stream

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(isr);
String st = br.readLine( ); //reads chars until eol and forms string

BITS Pilani, Pilani Campus


String Tokenizer
Consider the following program fragment:

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

BITS Pilani, Pilani Campus


String Tokenizer
We need to retrieve the four separate integers from the string.

str = 6 2 4 3 2 1

A token consists of a string of characters separated by a delimiter.

Delimiters consist of {space, tab, newline, return}

A StringTokenizer parses a String and extracts the individual tokens.

StringTokenizer st = new StringTokenizer (str); //create tokenizer and pass string


String s_temp;
while (st.hasMoreTokens( ) ) {
s_temp = st.nextToken( );
//now convert this string to an integer.

BITS Pilani, Pilani Campus


Wrapper Classes

For each of the primitive types there is a Wrapper class.

Primitive type object

int num1 = 6; Integer myInt = Integer(num1);


double num2 = 3.1416; Double pi = Double(num2);

In the statement Integer myInt = Integer(num1); an Integer object named


myInt is created and assigned a value equal to the contents of num1
Wrapper classes begin with an uppercase letter to distinguish from their
primitive type counterpart (int, long, short, double, float, byte, char, boolean).
int  Integer
double  Double
float  Float
char  Character

BITS Pilani, Pilani Campus


Wrapper Classes

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

BITS Pilani, Pilani Campus


Converting Tokenized String to Primitive Types

Return to the code for extracting tokens from the input string

int sum = 0, num;


String s;
while (st.hasMoreTokens( )) {
s = st.nextToken( );
//convert string to int
num = Integer.parseInt(s);
sum += num;
}

BITS Pilani, Pilani Campus


Review - Reading stream of integers from keyboard

Step 1 – Prompt user to enter multiple integers on one line

System.out.print(“Enter four integers separated by spaces: “);


Step 2 – Retrieve keyboard input as a stream of 16-bit chars (retuned as int)
InputStreamReader isr = new InputStreamReader(System.in);

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

Step 4 – Create StringTokenizer to extract tokens from the input string


StringTokenizer st = new StringTokenizer(str);

BITS Pilani, Pilani Campus


Review – continued

Step 5 – Parse the input string to extract tokens

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

int num = Integer.parseInt(s1);

BITS Pilani, Pilani Campus


Putting it all together
import java.io.*; //for keyboard input methods
import java.util.*; //for StringTokenizer
public class TotalNumbers {
public static void main (String [] args) throws java.io.IOException {
String str, s;
int sum = 0, num;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print(“Enter four integers separated by spaces: “);
str = br.readLine( );
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens( )) {
s = st.nextToken( );
num = Integer.parseInt(s);
sum += num;
}
}
}

BITS Pilani, Pilani Campus


Interactive Input
Using a Dialog box to request input data
Step 1 – Import swing package. import javax.swing.*;
Step 2 – Create an input dialog box (returns a String)

String str = JOptionPane.showInputDialog(“the message”);


Input
Input x

the message
?

OK Cancel

Step 3 – Write input value(s) in the text field //done by user


Step 4 – Click on command button (OK, Cancel) //done by user

BITS Pilani, Pilani Campus


Output to a Dialog Box

Types of Dialog Boxes icon

WARNING_MESSAGE !

QUESTION_MESSAGE ?

INFORMATION_MESSAGE

ERROR_MESSAGE

PLAIN_MESSAGE

BITS Pilani, Pilani Campus


Output Dialog Boxes
To create a dialog box for displaying output use showMessageDialog

JOptionPane.showMessageDialog(null, “message”, “title”,icon_type);

For example, the statement:

JOptionPane.showMessageDialog(null, “Little Programmers!”, “greetings”,


JOptionPane.PLAIN_MESSAGE);

produces
greetings X

Little Programmers!

OK

BITS Pilani, Pilani Campus


Output Dialog Boxes

Note that the icon-type field in the showDialogMessage( )


method is a static constant declared in class JOptionPane, and
must be referenced by a message to this class.

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.

Note! Without the final statement System.exit(0); a program that


ends with a message dialog box will still be active after the dialog box
has been closed.

BITS Pilani, Pilani Campus


An Interactive Program that Uses Dialog Boxes
import javax.swing.*; //for JOptionPane
import java.util.*; //for StringTokenizer
public class DialogExample {
public static void main(String [] args) {
String sInput, str;
int num, sum = 0;
sInput = JOptionPane.showInputDialog(“enter three integers:”);
StringTokenizer st = new StringTokenizer(sInput);
while (st.hasMoreTokens( ) ) {
str = st.nextToken( );
num = Integer.parseInt(str);
sum += num;
} //output the result to a dialog box
JOptionPane.showDialogMessage(null, “DialogExample Output”,
“the sum is: ”+ sum, JOptionPane.INFORMATION_MESSAGE);
System.exit(0); //needed to close program when using dialog box
}
}

BITS Pilani, Pilani Campus


Review

To perform interactive I/O using dialog boxes

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);

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus

You might also like