SlideShare uma empresa Scribd logo
1 de 43
CHAPTER 3: INTRODUCTION TO
OBJECTS AND INPUT/OUTPUT
JAVA PROGRAMMING:
FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN,
SECOND EDITION
2
Chapter Objectives
 Learn about objects and reference variables.
 Explore how to use predefined methods in a
program.
 Become familiar with the class String.
 Learn how to use input and output dialog boxes in a
program.
3
Chapter Objectives
 Explore how to format the output of decimal
numbers with the String method format.
 Become familiar with file input and output.
4
Object and Reference Variables
 Declare a reference variable of a class type.
 Allocate memory space for data.
 Instantiate an object of that class type.
 Store the address of the object in a reference
variable.
5
int x; //Line 1
String str; //Line 2
x = 45; //Line 3
str = "Java Programming"; //Line 4
Object and Reference Variables
6
String str;
str = "Hello there!";
Object and Reference Variables
7
 Primitive type variables directly store data into their memory
space.
 Reference variables store the address of the object containing
the data.
 An object is an instance of a class and the operator new is
used to instantiate an object.
Object and Reference Variables
8
Using Predefined Classes and
Methods in a Program
 There are many predefined packages, classes, and
methods in Java.
 Library: A collection of packages.
 Package: Contains several classes.
 Class: Contains several methods.
 Method: A set of instructions.
9
Using Predefined Classes and
Methods in a Program
To use a method you must know:
 Name of the class containing the method (Math).
 Name of the package containing the class
(java.lang).
 Name of the method - (pow), its has two parameters
 Math.pow(x, y) = xy
10
Using Predefined Classes and
Methods in a Program
 Example method call:
import java.lang; //imports package
Math.pow(2, 3); //calls power method
// in class Math
 Dot (.)operator: Used to access the method in the
class.
11
The class String
 String variables are reference variables.
 Given:
String name;
 Equivalent statements:
name = new String("Lisa Johnson");
name = "Lisa Johnson";
12
The class String
 A String object is an instance of class String.
 A String object with the value "Lisa Johnson" is
instantiated.
 The address of the object is stored in name.
 The new operator is unnecessary when instantiating Java
strings.
 String methods are called using the dot operator.
13
Some Commonly Used String Methods
14
Some Commonly Used String Methods
15
Some Commonly Used String Methods
16
Some Commonly Used String Methods
17
Input/Output
 Input data
 Format output
 Output results
 Format output
 Read from and write to files
18
Formatting Output with printf
 The syntax to use the method printf to produce output on the
standard output device is:
System.out.printf(formatString);
or
System.out.printf(formatString,
argumentList);
 formatString is a string specifying the format of the output and
argumentList is a list of arguments.
 argumentList is a list of arguments that consists of constant
values, variables, or expressions.
 If there is more than one argument in argumentList, the
arguments are separated with commas.
19
Formatting Output with printf
System.out.printf("Hello there!");
Consists of only the format string and the statement:
System.out.printf("There are %.2f inches in %d centimeters.%n",
centimeters / 2.54, centimeters);
 Consists of both the format string and argumentList.
 %.2f and %d are called format specifiers.
 By default, there is a one-to-one correspondence between format
specifiers and the arguments in argumentList.
 The first format specifier, %.2f, is matched with the first argument,
which is the expression centimeters / 2.54.
 The second format specifier, %d, is matched with the second argument,
which is centimeters.
 The format specifier %n positions the insertion point at the beginning of
the next line.
20
Formatting Output with printf
 A format specifier for general, character, and numeric types has the
following syntax:
%[argument_index$][flags][width][.precision]conversion
 The expressions in square brackets are optional. That is, they may or
may not appear in a format specifier.
 The optional argument_index is a (decimal) integer that indicates the
position of the argument in the argument list. The first argument is
referenced by "1$," the second by "2$," etc.
 The optional flags is a set of characters that modify the output format.
 The optional width is a (decimal) integer that indicates the minimum
number of characters to be written to the output.
 The optional precision is a (decimal) integer that is usually used to
restrict the number of characters.
 The required conversion is a character that indicates how the argument
should be formatted.
21
Formatting Output with printf
22
Parsing Numeric Strings
 A string consisting of only integers or decimal numbers is
called a numeric string.
 To convert a string consisting of an integer to a value of the
type int, we use the following expression:
Integer.parseInt(strExpression)
Integer.parseInt("6723") = 6723
Integer.parseInt("-823") = -823
23
Parsing Numeric Strings
 To convert a string consisting of a decimal number to a value
of the type float, we use the following expression:
Float.parseFloat(strExpression)
Float.parseFloat("34.56") = 34.56
Float.parseFloat("-542.97") = -542.97
 To convert a string consisting of a decimal number to a value
of the type double, we use the following expression:
Double.parseDouble(strExpression)
Double.parseDouble("345.78") = 345.78
Double.parseDouble("-782.873") = -782.873
24
Parsing Numeric Strings
 Integer, Float, and Double are classes designed to
convert a numeric string into a number.
 These classes are called wrapper classes.
 parseInt is a method of the class Integer, which
converts a numeric integer string into a value of the type
int.
 parseFloat is a method of the class Float and is used
to convert a numeric decimal string into an equivalent value
of the type float.
 parseDouble is a method of the class Double, which
is used to convert a numeric decimal string into an equivalent
value of the type double.
25
Using Dialog Boxes for
Input/Output
 Use a graphical user interface (GUI).
 class JOptionPane
 Contained in package javax.swing.
 Contains methods showInputDialog and
showMessageDialog.
 Syntax:
str = JOptionPane.showInputDialog(strExpression)
 Program must end with System.exit(0);
26
Parameters for the Method
showMessageDialog
27
JOptionPane Options for the
Parameter messageType
28
JOptionPane Example
29
Formatting the Output Using the
String Method format
Example 3-13
double x = 15.674;
double y = 235.73;
double z = 9525.9864;
int num = 83;
String str;
30
File Input/Output
 File: An area in secondary storage used to hold
information.
 You can also initialize a Scanner object to input
sources other than the standard input device by
passing an appropriate argument in place of the
object System.in.
 We make use of the class FileReader.
31
File Input/Output
 Suppose that the input data is stored in a file, say
prog.dat, and this file is on the floppy disk A.
 The following statement creates the Scanner object
inFile and initializes it to the file prog.dat:
 Scanner inFile = new Scanner
(new FileReader("a:prog.dat"));
 You use the object inFile to input data from the file
prog.dat just the way you used the object console to
input data from the standard input device using the
methods next, nextInt, nextDouble, and so on.
32
File Input/Output
Java file I/O process:
1. Import necessary classes from the packages
java.util and java.io into the program.
2. Create and associate appropriate objects with the
input/output sources.
3. Use the appropriate methods associated with the
variables created in Step 2 to input/output data.
4. Close the files.
33
Example 3-16
Suppose an input file, say employeeData.txt, consists of the
following data:
Emily Johnson 45 13.50
Scanner inFile = new Scanner
(new FileReader("a:employeeData.txt"));
String firstName;
String lastName;
double hoursWorked;
double payRate;
double wages;
firstName = inFile.next();
lastName = inFile.next();
hoursWorked = inFile.nextDouble();
payRate = inFile.nextDouble();
wages = hoursWorked * payRate;
inFile.close(); //close the input file
File Input/Output
34
Storing (Writing) Output in a File
 To store the output of a program in a file, you use the class
PrintWriter.
 Declare a PrintWriter variable and associate this variable
with the destination.
 Suppose the output is to be stored in the file prog.out on
floppy disk A.
 Consider the following statement:
PrintWriter outFile = new
PrintWriter("a:prog.out");
 This statement creates the PrintWriter object outFile
and associates it with the file prog.out on floppy disk A.
 You can now use the methods print, println, printf,
and flush with outFile in the same way they have been
used with the object System.out.
35
Storing (Writing) Output in a File
 The statement:
outFile.println("The paycheck is: $" + pay);
stores the output—The paycheck is: $565.78—in the file
prog.out. This statement assumes that the value of the variable
pay is 565.78.
 Step 4 requires closing the file. You close the input and output files
by using the method close.
inFile.close();
outFile.close();
 Closing the output file ensures that the buffer holding the output
will be emptied; that is, the entire output generated by the program
will be sent to the output file.
36
(throws clause)
 During program execution, various things can happen; for example,
division by zero or inputting a letter for a number.
 In such cases, we say that an exception has occurred.
 If an exception occurs in a method, then the method should either
handle the exception or throw it for the calling environment to
handle.
 If an input file does not exist, the program throws a
FileNotFoundException.
 If an output file cannot be created or accessed, the program throws
a FileNotFoundException.
 For the next few chapters, we will simply throw the exceptions.
 Because we do not need the method main to handle the
FileNotFoundException exception, we will include a command in
the heading of the method main to throw the
FileNotFoundException exception.
Storing (Writing) Output in a File
37
Skeleton of I/O Program
38
Programming Example: Movie
Ticket Sale and Donation to Charity
 Input: Movie name, adult ticket price, child ticket price, number of adult
tickets sold, number of child tickets sold, percentage of gross amount to
be donated to charity.
 Output:
39
Programming Example: Movie Ticket
Sale and Donation to Charity
1. Import appropriate packages.
2. Get inputs from user using
JOptionPane.showInputDialog.
3. Perform appropriate calculations.
4. Display output using
JOptionPane.showMessageDialog.
40
Programming Example:
Student Grade
 Input: File containing student’s first name, last
name, five test scores.
 Output: File containing student’s first name, last
name, five test scores, average of five test scores.
41
Programming Example:
Student Grade
1. Import appropriate packages.
2. Get input from file using the classes Scanner
and FileReader.
3. Read and calculate the average of test scores.
4. Write to output file using the class
PrintWriter.
5. Close files.
42
Chapter Summary
 Primitive type variables store data into their
memory space.
 Reference variables store the address of the object
containing the data.
 An object is an instance of a class.
 Operator new is used to instantiate an object.
 Garbage collection reclaims memory that is not
being used.
43
Chapter Summary
 To use a predefined method, you must know its
name and the class and package it belongs to.
 The dot (.) operator is used to access a certain
method in a class.
 Methods of the class String are used to
manipulate input and output data.
 Dialog boxes can be used to input data and output
results.
 Data can be read from and written to files.
 Data can be formatted using the String method
format.

Mais conteúdo relacionado

Mais procurados

Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
Varun Mahajan
 
17. Computer System Configuration And Methods
17. Computer System   Configuration And Methods17. Computer System   Configuration And Methods
17. Computer System Configuration And Methods
New Era University
 
Cryptography (Distributed computing)
Cryptography (Distributed computing)Cryptography (Distributed computing)
Cryptography (Distributed computing)
Sri Prasanna
 

Mais procurados (20)

Problem Solving and Programming
Problem Solving and ProgrammingProblem Solving and Programming
Problem Solving and Programming
 
Software Engineering by Pankaj Jalote
Software Engineering by Pankaj JaloteSoftware Engineering by Pankaj Jalote
Software Engineering by Pankaj Jalote
 
Flowshop scheduling
Flowshop schedulingFlowshop scheduling
Flowshop scheduling
 
SRS(software requirement specification)
SRS(software requirement specification)SRS(software requirement specification)
SRS(software requirement specification)
 
A presentation on software crisis
A presentation on software crisisA presentation on software crisis
A presentation on software crisis
 
Lecture 1 introduction to software engineering 1
Lecture 1   introduction to software engineering 1Lecture 1   introduction to software engineering 1
Lecture 1 introduction to software engineering 1
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
 
17. Computer System Configuration And Methods
17. Computer System   Configuration And Methods17. Computer System   Configuration And Methods
17. Computer System Configuration And Methods
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
UML Case Tools
UML Case ToolsUML Case Tools
UML Case Tools
 
Software metrics
Software metricsSoftware metrics
Software metrics
 
Cryptography (Distributed computing)
Cryptography (Distributed computing)Cryptography (Distributed computing)
Cryptography (Distributed computing)
 
Types of grammer - TOC
Types of grammer - TOCTypes of grammer - TOC
Types of grammer - TOC
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
 
Rad model
Rad modelRad model
Rad model
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
 
Reusability
ReusabilityReusability
Reusability
 
OPERATING SYSTEM
OPERATING SYSTEMOPERATING SYSTEM
OPERATING SYSTEM
 
PRESCRIPTIVE PROCESS MODEL(SOFTWARE ENGINEERING)
PRESCRIPTIVE PROCESS MODEL(SOFTWARE ENGINEERING)PRESCRIPTIVE PROCESS MODEL(SOFTWARE ENGINEERING)
PRESCRIPTIVE PROCESS MODEL(SOFTWARE ENGINEERING)
 
Operating System: Deadlock
Operating System: DeadlockOperating System: Deadlock
Operating System: Deadlock
 

Destaque

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
Ahmad Idrees
 

Destaque (20)

Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing
 
What is business
What is businessWhat is business
What is business
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement
 
Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSE
 

Semelhante a Introduction to objects and inputoutput

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
9781439035665 ppt ch03
9781439035665 ppt ch039781439035665 ppt ch03
9781439035665 ppt ch03
Terry Yoast
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
fashionbigchennai
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 

Semelhante a Introduction to objects and inputoutput (20)

Chap03
Chap03Chap03
Chap03
 
Chap03
Chap03Chap03
Chap03
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
9781439035665 ppt ch03
9781439035665 ppt ch039781439035665 ppt ch03
9781439035665 ppt ch03
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
F# Console class
F# Console classF# Console class
F# Console class
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Java execise
Java execiseJava execise
Java execise
 
OOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixOOP, Networking, Linux/Unix
OOP, Networking, Linux/Unix
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Java stream
Java streamJava stream
Java stream
 

Mais de Ahmad Idrees

Mais de Ahmad Idrees (7)

Control structures i
Control structures i Control structures i
Control structures i
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know about
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Introduction to objects and inputoutput

  • 1. CHAPTER 3: INTRODUCTION TO OBJECTS AND INPUT/OUTPUT JAVA PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN, SECOND EDITION
  • 2. 2 Chapter Objectives  Learn about objects and reference variables.  Explore how to use predefined methods in a program.  Become familiar with the class String.  Learn how to use input and output dialog boxes in a program.
  • 3. 3 Chapter Objectives  Explore how to format the output of decimal numbers with the String method format.  Become familiar with file input and output.
  • 4. 4 Object and Reference Variables  Declare a reference variable of a class type.  Allocate memory space for data.  Instantiate an object of that class type.  Store the address of the object in a reference variable.
  • 5. 5 int x; //Line 1 String str; //Line 2 x = 45; //Line 3 str = "Java Programming"; //Line 4 Object and Reference Variables
  • 6. 6 String str; str = "Hello there!"; Object and Reference Variables
  • 7. 7  Primitive type variables directly store data into their memory space.  Reference variables store the address of the object containing the data.  An object is an instance of a class and the operator new is used to instantiate an object. Object and Reference Variables
  • 8. 8 Using Predefined Classes and Methods in a Program  There are many predefined packages, classes, and methods in Java.  Library: A collection of packages.  Package: Contains several classes.  Class: Contains several methods.  Method: A set of instructions.
  • 9. 9 Using Predefined Classes and Methods in a Program To use a method you must know:  Name of the class containing the method (Math).  Name of the package containing the class (java.lang).  Name of the method - (pow), its has two parameters  Math.pow(x, y) = xy
  • 10. 10 Using Predefined Classes and Methods in a Program  Example method call: import java.lang; //imports package Math.pow(2, 3); //calls power method // in class Math  Dot (.)operator: Used to access the method in the class.
  • 11. 11 The class String  String variables are reference variables.  Given: String name;  Equivalent statements: name = new String("Lisa Johnson"); name = "Lisa Johnson";
  • 12. 12 The class String  A String object is an instance of class String.  A String object with the value "Lisa Johnson" is instantiated.  The address of the object is stored in name.  The new operator is unnecessary when instantiating Java strings.  String methods are called using the dot operator.
  • 13. 13 Some Commonly Used String Methods
  • 14. 14 Some Commonly Used String Methods
  • 15. 15 Some Commonly Used String Methods
  • 16. 16 Some Commonly Used String Methods
  • 17. 17 Input/Output  Input data  Format output  Output results  Format output  Read from and write to files
  • 18. 18 Formatting Output with printf  The syntax to use the method printf to produce output on the standard output device is: System.out.printf(formatString); or System.out.printf(formatString, argumentList);  formatString is a string specifying the format of the output and argumentList is a list of arguments.  argumentList is a list of arguments that consists of constant values, variables, or expressions.  If there is more than one argument in argumentList, the arguments are separated with commas.
  • 19. 19 Formatting Output with printf System.out.printf("Hello there!"); Consists of only the format string and the statement: System.out.printf("There are %.2f inches in %d centimeters.%n", centimeters / 2.54, centimeters);  Consists of both the format string and argumentList.  %.2f and %d are called format specifiers.  By default, there is a one-to-one correspondence between format specifiers and the arguments in argumentList.  The first format specifier, %.2f, is matched with the first argument, which is the expression centimeters / 2.54.  The second format specifier, %d, is matched with the second argument, which is centimeters.  The format specifier %n positions the insertion point at the beginning of the next line.
  • 20. 20 Formatting Output with printf  A format specifier for general, character, and numeric types has the following syntax: %[argument_index$][flags][width][.precision]conversion  The expressions in square brackets are optional. That is, they may or may not appear in a format specifier.  The optional argument_index is a (decimal) integer that indicates the position of the argument in the argument list. The first argument is referenced by "1$," the second by "2$," etc.  The optional flags is a set of characters that modify the output format.  The optional width is a (decimal) integer that indicates the minimum number of characters to be written to the output.  The optional precision is a (decimal) integer that is usually used to restrict the number of characters.  The required conversion is a character that indicates how the argument should be formatted.
  • 22. 22 Parsing Numeric Strings  A string consisting of only integers or decimal numbers is called a numeric string.  To convert a string consisting of an integer to a value of the type int, we use the following expression: Integer.parseInt(strExpression) Integer.parseInt("6723") = 6723 Integer.parseInt("-823") = -823
  • 23. 23 Parsing Numeric Strings  To convert a string consisting of a decimal number to a value of the type float, we use the following expression: Float.parseFloat(strExpression) Float.parseFloat("34.56") = 34.56 Float.parseFloat("-542.97") = -542.97  To convert a string consisting of a decimal number to a value of the type double, we use the following expression: Double.parseDouble(strExpression) Double.parseDouble("345.78") = 345.78 Double.parseDouble("-782.873") = -782.873
  • 24. 24 Parsing Numeric Strings  Integer, Float, and Double are classes designed to convert a numeric string into a number.  These classes are called wrapper classes.  parseInt is a method of the class Integer, which converts a numeric integer string into a value of the type int.  parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float.  parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double.
  • 25. 25 Using Dialog Boxes for Input/Output  Use a graphical user interface (GUI).  class JOptionPane  Contained in package javax.swing.  Contains methods showInputDialog and showMessageDialog.  Syntax: str = JOptionPane.showInputDialog(strExpression)  Program must end with System.exit(0);
  • 26. 26 Parameters for the Method showMessageDialog
  • 27. 27 JOptionPane Options for the Parameter messageType
  • 29. 29 Formatting the Output Using the String Method format Example 3-13 double x = 15.674; double y = 235.73; double z = 9525.9864; int num = 83; String str;
  • 30. 30 File Input/Output  File: An area in secondary storage used to hold information.  You can also initialize a Scanner object to input sources other than the standard input device by passing an appropriate argument in place of the object System.in.  We make use of the class FileReader.
  • 31. 31 File Input/Output  Suppose that the input data is stored in a file, say prog.dat, and this file is on the floppy disk A.  The following statement creates the Scanner object inFile and initializes it to the file prog.dat:  Scanner inFile = new Scanner (new FileReader("a:prog.dat"));  You use the object inFile to input data from the file prog.dat just the way you used the object console to input data from the standard input device using the methods next, nextInt, nextDouble, and so on.
  • 32. 32 File Input/Output Java file I/O process: 1. Import necessary classes from the packages java.util and java.io into the program. 2. Create and associate appropriate objects with the input/output sources. 3. Use the appropriate methods associated with the variables created in Step 2 to input/output data. 4. Close the files.
  • 33. 33 Example 3-16 Suppose an input file, say employeeData.txt, consists of the following data: Emily Johnson 45 13.50 Scanner inFile = new Scanner (new FileReader("a:employeeData.txt")); String firstName; String lastName; double hoursWorked; double payRate; double wages; firstName = inFile.next(); lastName = inFile.next(); hoursWorked = inFile.nextDouble(); payRate = inFile.nextDouble(); wages = hoursWorked * payRate; inFile.close(); //close the input file File Input/Output
  • 34. 34 Storing (Writing) Output in a File  To store the output of a program in a file, you use the class PrintWriter.  Declare a PrintWriter variable and associate this variable with the destination.  Suppose the output is to be stored in the file prog.out on floppy disk A.  Consider the following statement: PrintWriter outFile = new PrintWriter("a:prog.out");  This statement creates the PrintWriter object outFile and associates it with the file prog.out on floppy disk A.  You can now use the methods print, println, printf, and flush with outFile in the same way they have been used with the object System.out.
  • 35. 35 Storing (Writing) Output in a File  The statement: outFile.println("The paycheck is: $" + pay); stores the output—The paycheck is: $565.78—in the file prog.out. This statement assumes that the value of the variable pay is 565.78.  Step 4 requires closing the file. You close the input and output files by using the method close. inFile.close(); outFile.close();  Closing the output file ensures that the buffer holding the output will be emptied; that is, the entire output generated by the program will be sent to the output file.
  • 36. 36 (throws clause)  During program execution, various things can happen; for example, division by zero or inputting a letter for a number.  In such cases, we say that an exception has occurred.  If an exception occurs in a method, then the method should either handle the exception or throw it for the calling environment to handle.  If an input file does not exist, the program throws a FileNotFoundException.  If an output file cannot be created or accessed, the program throws a FileNotFoundException.  For the next few chapters, we will simply throw the exceptions.  Because we do not need the method main to handle the FileNotFoundException exception, we will include a command in the heading of the method main to throw the FileNotFoundException exception. Storing (Writing) Output in a File
  • 38. 38 Programming Example: Movie Ticket Sale and Donation to Charity  Input: Movie name, adult ticket price, child ticket price, number of adult tickets sold, number of child tickets sold, percentage of gross amount to be donated to charity.  Output:
  • 39. 39 Programming Example: Movie Ticket Sale and Donation to Charity 1. Import appropriate packages. 2. Get inputs from user using JOptionPane.showInputDialog. 3. Perform appropriate calculations. 4. Display output using JOptionPane.showMessageDialog.
  • 40. 40 Programming Example: Student Grade  Input: File containing student’s first name, last name, five test scores.  Output: File containing student’s first name, last name, five test scores, average of five test scores.
  • 41. 41 Programming Example: Student Grade 1. Import appropriate packages. 2. Get input from file using the classes Scanner and FileReader. 3. Read and calculate the average of test scores. 4. Write to output file using the class PrintWriter. 5. Close files.
  • 42. 42 Chapter Summary  Primitive type variables store data into their memory space.  Reference variables store the address of the object containing the data.  An object is an instance of a class.  Operator new is used to instantiate an object.  Garbage collection reclaims memory that is not being used.
  • 43. 43 Chapter Summary  To use a predefined method, you must know its name and the class and package it belongs to.  The dot (.) operator is used to access a certain method in a class.  Methods of the class String are used to manipulate input and output data.  Dialog boxes can be used to input data and output results.  Data can be read from and written to files.  Data can be formatted using the String method format.