SlideShare a Scribd company logo
1 of 15
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

What's hot (18)

Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
(6) collections algorithms
(6) collections algorithms(6) collections algorithms
(6) collections algorithms
 
Python-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityPython-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutability
 
Scanner class
Scanner classScanner class
Scanner class
 
Java stream
Java streamJava stream
Java stream
 
package
packagepackage
package
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java IO
Java IOJava IO
Java IO
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Java Streams
Java StreamsJava Streams
Java Streams
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Class and object
Class and objectClass and object
Class and object
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Inputstream
InputstreamInputstream
Inputstream
 

Similar to Dr. Rajeshree Khande Java Interactive input

KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerAiman Hud
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3Syed Farjad Zia Zaidi
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptxRathanMB
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptxssuser9d7049
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 

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

Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
unit 1.docx
unit 1.docxunit 1.docx
unit 1.docx
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 

More from DrRajeshreeKhande

More from DrRajeshreeKhande (20)

.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
Exception Handling in .NET F#
Exception Handling in .NET F#Exception Handling in .NET F#
Exception Handling in .NET F#
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
F# Console class
F# Console classF# Console class
F# Console class
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
 
MS Office for Beginners
MS Office for BeginnersMS Office for Beginners
MS Office for Beginners
 
Java Multi-threading programming
Java Multi-threading programmingJava Multi-threading programming
Java Multi-threading programming
 
Java String class
Java String classJava String class
Java String class
 
JAVA AWT components
JAVA AWT componentsJAVA AWT components
JAVA AWT components
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Dr. Rajeshree Khande : Java Basics
Dr. Rajeshree Khande  : Java BasicsDr. Rajeshree Khande  : Java Basics
Dr. Rajeshree Khande : Java Basics
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

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