SlideShare a Scribd company logo
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
RAJESHREE KHANDE1
Reading information into a program.
RAJESHREE KHANDE2
Writing information from a program
User input classes
RAJESHREE KHANDE3
 To get user input, use the BufferedReader and
InputStreamReader classes.
 The InputStreamReader class - reads the user's
input.
 The BufferedReader class - buffers the user's
input to make it work more efficiently.
Keyboard Input
The System class in java provides an
InputStream object: System.in
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.
RAJESHREE KHANDE4
Keyboard Input
BufferedReader
InputStreamReader
int stringbyte
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String st = br.readLine( );
import java.io.*; //for keyboard input stream
//reads chars until eol and forms string
RAJESHREE KHANDE5
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
RAJESHREE KHANDE6
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.
RAJESHREE KHANDE7
StringTokenizer :Method
RAJESHREE KHANDE8
 int countTokens()
Calculates the number of times that this
tokenizer's nextToken method can be called before it
generates an exception.
 boolean hasMoreElements()
Returns the same value as the hasMoreTokens
method.
 boolean hasMoreTokens()
Tests if there are more tokens available from this
tokenizer's string.
StringTokenizer :Method
RAJESHREE KHANDE9
 Object nextElement()
Returns the same value as the nextToken method,
except that its declared return value is Object rather
than String.
 String nextToken()
Returns the next token from this string
tokenizer.
 String nextToken(String delim)
Returns the next token in this string tokenizer's
string.
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
RAJESHREE KHANDE10
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 Classes
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
RAJESHREE KHANDE11
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;
}
RAJESHREE KHANDE12
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( );
Step 4 – Create StringTokenizer to extract tokens from the input string
StringTokenizer st = new StringTokenizer(str);
Need to throw java.io.IOException in function in
which it is used
RAJESHREE KHANDE13
Review – cont.
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);
RAJESHREE KHANDE14
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: “); //prompt
str = br.readLine( );
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens( )) {
s = st.nextToken( );
num = Integer.parseInt(s);
sum += num; }
}
} RAJESHREE KHANDE15

More Related Content

PPT
ppt on scanner class
PPTX
Buffer and scanner
PPTX
Java input
PPTX
Python for Beginners(v1)
PPT
Taking User Input in Java
PPT
Stream Based Input Output
PPTX
PPTX
Python The basics
ppt on scanner class
Buffer and scanner
Java input
Python for Beginners(v1)
Taking User Input in Java
Stream Based Input Output
Python The basics

What's hot (18)

DOCX
Oodp mod4
PPTX
Programming in Python
ODP
(6) collections algorithms
PPTX
Python-04| Fundamental data types vs immutability
PPT
Scanner class
PPT
Java stream
PPTX
package
PPSX
Programming with Python
PPTX
Understanding java streams
PDF
Java IO
PPT
Chapter 12 - File Input and Output
PPTX
Python for Beginners(v3)
PPT
Java Streams
ODP
IO In Java
PPTX
Class and object
PPTX
Handling inputs via scanner class
TXT
Inputstream
PDF
Java I/o streams
Oodp mod4
Programming in Python
(6) collections algorithms
Python-04| Fundamental data types vs immutability
Scanner class
Java stream
package
Programming with Python
Understanding java streams
Java IO
Chapter 12 - File Input and Output
Python for Beginners(v3)
Java Streams
IO In Java
Class and object
Handling inputs via scanner class
Inputstream
Java I/o streams
Ad

Similar to Dr. Rajeshree Khande - Java Interactive input (20)

PPTX
Lecture 3.pptx
PPTX
Computer programming 2 Lesson 12
PPTX
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
DOCX
Unit IV Notes.docx
PDF
Lecture 2 java.pdf
PPTX
DAY_1.3.pptx
PDF
Java IO Stream, the introduction to Streams
PPTX
Introduction on basic python and it's application
PPT
file handling in object oriented programming through java
PPTX
File Input and output.pptx
PPTX
String Handling, Inheritance, Packages and Interfaces
DOCX
unit 1.docx
PPTX
Introduction To Programming with Python-3
PPT
python1.ppt
PPTX
Java Input and Output
PPTX
Java Unit 2(Part 1)
PPTX
CH1 ARRAY (1).pptx
PPTX
Computer science input and output BASICS.pptx
PPTX
Python 3.pptx
DOCX
Unitii classnotes
Lecture 3.pptx
Computer programming 2 Lesson 12
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
Unit IV Notes.docx
Lecture 2 java.pdf
DAY_1.3.pptx
Java IO Stream, the introduction to Streams
Introduction on basic python and it's application
file handling in object oriented programming through java
File Input and output.pptx
String Handling, Inheritance, Packages and Interfaces
unit 1.docx
Introduction To Programming with Python-3
python1.ppt
Java Input and Output
Java Unit 2(Part 1)
CH1 ARRAY (1).pptx
Computer science input and output BASICS.pptx
Python 3.pptx
Unitii classnotes
Ad

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Basic Mud Logging Guide for educational purpose
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Insiders guide to clinical Medicine.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Lesson notes of climatology university.
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
O7-L3 Supply Chain Operations - ICLT Program
Basic Mud Logging Guide for educational purpose
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial diseases, their pathogenesis and prophylaxis
Insiders guide to clinical Medicine.pdf
01-Introduction-to-Information-Management.pdf
Cell Types and Its function , kingdom of life
102 student loan defaulters named and shamed – Is someone you know on the list?
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Lesson notes of climatology university.
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx

Dr. Rajeshree Khande - Java Interactive input

  • 1. 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 RAJESHREE KHANDE1
  • 2. Reading information into a program. RAJESHREE KHANDE2 Writing information from a program
  • 3. User input classes RAJESHREE KHANDE3  To get user input, use the BufferedReader and InputStreamReader classes.  The InputStreamReader class - reads the user's input.  The BufferedReader class - buffers the user's input to make it work more efficiently.
  • 4. Keyboard Input The System class in java provides an InputStream object: System.in 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. RAJESHREE KHANDE4
  • 5. Keyboard Input BufferedReader InputStreamReader int stringbyte InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String st = br.readLine( ); import java.io.*; //for keyboard input stream //reads chars until eol and forms string RAJESHREE KHANDE5
  • 6. 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 RAJESHREE KHANDE6
  • 7. 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. RAJESHREE KHANDE7
  • 8. StringTokenizer :Method RAJESHREE KHANDE8  int countTokens() Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.  boolean hasMoreElements() Returns the same value as the hasMoreTokens method.  boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.
  • 9. StringTokenizer :Method RAJESHREE KHANDE9  Object nextElement() Returns the same value as the nextToken method, except that its declared return value is Object rather than String.  String nextToken() Returns the next token from this string tokenizer.  String nextToken(String delim) Returns the next token in this string tokenizer's string.
  • 10. 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 RAJESHREE KHANDE10
  • 11. 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 Classes 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 RAJESHREE KHANDE11
  • 12. 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; } RAJESHREE KHANDE12
  • 13. 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( ); Step 4 – Create StringTokenizer to extract tokens from the input string StringTokenizer st = new StringTokenizer(str); Need to throw java.io.IOException in function in which it is used RAJESHREE KHANDE13
  • 14. Review – cont. 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); RAJESHREE KHANDE14
  • 15. 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: “); //prompt str = br.readLine( ); StringTokenizer st = new StringTokenizer(str); while (st.hasMoreTokens( )) { s = st.nextToken( ); num = Integer.parseInt(s); sum += num; } } } RAJESHREE KHANDE15