You are on page 1of 6

2/26/2014

Java Programming: From Problem Analysis to Program Design, 5e

Chapter 3 Introduction to Objects and Input/Output


*

Chapter Objectives Learn about objects and reference variables Explore how to use predefined methods in a program ecome familiar with the class !tring Learn how to use input and output dialog boxes in a program Chapter Objectives (continue ! Explore how to format the output of decimal numbers with the !tring method format ecome familiar with file input and output Object an "e#erence $ariables "eclare a reference variable of a class t#pe $ In %ava& variables such as str are call reference variables $ 'llocate memor# space for data $ Instantiate an object of that class t#pe !tore the address of the object in a reference variable Object an "e#erence $ariables (continue ! int x( //Line ) !tring str( //Line * x + ,-( //Line 3 str + .%ava /rogramming.( //Line , Object an "e#erence $ariables (continue ! Object an "e#erence $ariables (continue ! Object an "e#erence $ariables (continue ! %sing Pre e#ine Classes an &etho s in a Program 0here are man# predefined classes 1pac2ages3& and methods 1collection of instructions3 in %ava Class Libraries4 collection of pac2ages /ac2age4 contains several classes Class4 contains several methods 5ethod4 set of instructions %sing Pre e#ine Classes an &etho s in a Program (continue ! 0o use a method& #ou must 2now4 $ 6ame of the class containing method 15ath3 $ 6ame of the pac2age containing class 1java7lang3 $ 6ame of the method 8 1pow3& it has two 1actual3 parameters $ 5ath7pow1x& #3 + x# %sing Pre e#ine Classes an &etho s in a Program (continue ! Example method call import java7lang( //imports pac2age 5ath7pow1*& 33( //calls power method // in class 5ath "ot 173 operator4 used to access the method in the class is called the member access operator 'he class (tring !tring variables are reference variables 9iven4 !tring name(

: ; < = )>

))

)*

)3

2/26/2014

),

)-

!tring name( $ !imilar statements4 name + new !tring1.Lisa %ohnson.3( name + .Lisa %ohnson.( 'he class (tring (continue ! ' !tring object is an instance of class !tring 0he address of a !tring object with the value .Lisa %ohnson. is stored in name !tring methods are called using the dot operator 'he class (tring (continue ! sentence + ./rogramming with %ava.( (ome Commonly %se (tring &etho s (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! )nput*Output Input data ?ormat output Output results ?ormat output @ead from and write to files Formatting Output +ith print# ' s#ntax to use the method printf to produce output on the standard output device is4 !#stem7out7printf1format!tring3( or4 !#stem7out7printf1format!tring& argumentList3( format!tring is a string specif#ing the format of the output& and argumentList is a list of arguments Formatting Output +ith print# (continue ! argumentList is a list of arguments that consists of constant values& variables& or expressions If there is more than one argument in argumentList& then the arguments are separated with commas Formatting Output +ith print# (continue ! !#stem7out7printf1.Aello thereB.3( consists of onl# the format string& and the statement4 !#stem7out7printf1.0here are C7*f inches in Cd centimeters7Cn.& centimeters / *7-,& centimeters3( consists of both the format string and argumentList Formatting Output +ith print# (continue ! C7*f and Cd are called format specifiers # default& there is a one8to8one correspondence between format specifiers and the arguments in argumentList 0he first format specifier C7*f is matched with the first argument& which is the expression centimeters / *7-,

): ); )< )= *> *)

**

*3

*,

*-

2/26/2014

*:

expression centimeters / *7-, 0he second format specifier Cd is matched with the second argument& which is centimeters Formatting Output +ith print# (continue ! 0he format specifier Cn positions the insertion point at the beginning of the next line ' format specifier for general& character& and numeric t#pes has the following s#ntax4 0he expressions in sDuare brac2ets are optional( the# ma# or ma# not appear in a format specifier Formatting Output +ith print# (continue ! 0he option argumentEindex is a 1decimal3 integer indicating the position of the argument in the argument list $ 0he first argument is referenced b# .)F.& the second b# .*F.& etc7 0he option flags is a set of characters that modif# the output format 0he option width is a 1decimal3 integer indicating the minimum number of characters to be written to the output Formatting Output +ith print# (continue ! 0he option precision is a 1decimal3 integer usuall# used to restrict the number of characters 0he reDuired conversion is a character indicating how the argument should be formatted Formatting Output +ith print# (continue !

*;

*<

*= 3> 3) 3* 33 3, 33: 3; 3< 3= ,> ,) ,*

Parsing ,umeric (trings Parsing ,umeric (trings (continue ! Parsing ,umeric (trings (continue ! 370o convert a string consisting of a decimal number to a value of the t#pe double& we use the following expression4 "ouble7parse"ouble1strExpression3 "ouble7parse"ouble1.3,-7;<.3 + 3,-7;< "ouble7parse"ouble1.8;<*7<;3.3 + 8;<*7<;3

,3 ,,

Parsing ,umeric (trings (continue ! Parsing ,umeric (trings (continue ! parse?loat is a method of the class ?loat and is used to convert a numeric decimal string into an eDuivalent value of the t#pe float parse"ouble is a method of the class "ouble& which is used to convert a numeric

2/26/2014

,-

,: ,; ,< ,= ->

-)

-*

-3

-, --

-:

parse"ouble is a method of the class "ouble& which is used to convert a numeric decimal string into an eDuivalent value of the t#pe double %sing Dialog -o.es #or )nput*Output Gse a graphical user interface 19GI3 class %Option/ane $ Contained in pac2age javax7swing $ Contains methods showInput"ialog and show5essage"ialog !#ntax str + %Option/ane7showInput"ialog1strExpression3 /rogram must end with !#stem7exit1>3( %sing Dialog -o.es #or )nput*Output (continue ! Parameters #or the &etho sho+&essageDialog JOptionPane Options #or the Parameter message'ype JOptionPane /.ample Formatting the Output %sing the (tring &etho #ormat Example 38)3 double x + )-7:;,( double # + *3-7;3( double H + =-*-7=<:,( int num + <3( !tring str( File )nput*Output ?ile4 area in secondar# storage used to hold information Iou can also initialiHe a !canner object to input sources other than the standard input device b# passing an appropriate argument in place of the object !#stem7in Je ma2e use of the class ?ile@eader File )nput*Output (continue ! !uppose that the input data is stored in a file& sa# prog7dat& and this file is on the flopp# dis2 ' 0he following statement creates the !canner object in?ile and initialiHes it to the file prog7dat !canner in?ile + new !canner 1new ?ile@eader1.prog7dat.33( File )nput*Output (continue ! 6ext& #ou use the object in?ile to input data from the file prog7dat just the wa# #ou used the object console to input data from the standard input device using the methods next& nextInt& next"ouble& and so on File )nput*Output (continue ! File )nput*Output (continue ! %ava file I/O process 1!0E/!3 )7 Import necessar# classes from the pac2ages java7util and java7io into the program *7 Create and associate appropriate objects with the input/output sources 37 Gse the appropriate methods associated with the variables created in !tep * to input/output data ,7 Close the files File )nput*Output (continue ! Example 38): !uppose an input file& sa# emplo#ee"ata7txt& consists of the following data4 Emil# %ohnson ,- )37->

2/26/2014

Emil# %ohnson ,- )37-> !canner in?ile + new !canner 1new ?ile@eader1.emplo#ee"ata7txt.33( !tring first6ame( !tring last6ame( double hoursJor2ed( double pa#@ate( double wages( first6ame + in?ile7next13( last6ame + in?ile7next13( hoursJor2ed + in?ile7next"ouble13( pa#@ate + in?ile7next"ouble13( wages + hoursJor2ed K pa#@ate( in?ile7close13( //close the input file (toring (0riting! Output to a File 0o store the output of a program in a file& #ou use the class /rintJriter "eclare a /rintJriter variable and associate this variable with the destination !uppose the output is to be stored in the file prog7out (toring (0riting! Output to a File (continue ! Consider the following statement4 /rintJriter out?ile + new /rintJriter1.prog7out.3( 0his statement creates the /rintJriter object out?ile and associates it with the file prog7out Iou can now use the methods print& println& and printf with out?ile just the same wa# the# have been used with the object !#stem7out (toring (0riting! Output to a File (continue ! 0he statement4 out?ile7println1.0he pa#chec2 is4 F. L pa#3( stores the outputM0he pa#chec2 is4 F-:-7;<M in the file prog7out 80his statement assumes that the value of the variable pa# is F-:-7;< (toring (0riting! Output to a File (continue ! !tep , reDuires closing the file( #ou close the input and output files b# using the method close in?ile7close13( out?ile7close13( Closing the output file ensures that the buffer holding the output will be emptied( that is& the entire output generated b# the program will be sent to the output file thro+s Clause thro+s Clause (continue !

-;

-<

-=

:>

:) :*

2/26/2014

:3 :,

:-

::

If an output file cannot be created or accessed& the program throws a ?ile6ot?oundException ?or the next few chapters& we will simpl# throw the exceptions ecause we do not need the method main to handle the ?ile6ot?oundException exception& we will include a command in the heading of the method main to throw the ?ile6ot?oundException exception (1eleton o# )*O Program Programming /.ample: &ovie 'ic1et (ale an Donation to Charity Input4 movie name& adult tic2et price& child tic2et price& number of adult tic2ets sold& number of child tic2ets sold& percentage of gross amount to be donated to charit# Output4 Programming /.ample: &ovie 'ic1et (ale an Donation to Charity (continue ! Import appropriate pac2ages 9et inputs from user using %Option/ane7showInput"ialog /erform appropriate calculations "ispla# output using %Option/ane7show5essage"ialog Programming /.ample: (tu ent 2ra e Input4 file containing studentNs first name& last name& five test scores Output4 file containing studentNs first name& last name& five test scores& average of five test scores Programming /.ample: (tu ent 2ra e (continue ! Import appropriate pac2ages 9et input from file using the classes !canner and ?ile@eader @ead and calculate the average of test scores Jrite to output file using the class /rintJriter Close files Chapter (ummary /rimitive t#pe variables store data into their memor# space @eference variables store the address of the object containing the data 'n object is an instance of a class Chapter (ummary (continue ! Operator new is used to instantiate an object 9arbage collection is reclaiming memor# not being used 0o use a predefined method& #ou must 2now its name and the class and pac2age it belongs to 0he dot 173 operator is used to access a certain method in a class Chapter (ummary (continue ! 5ethods of the class !tring are used to manipulate input and output data "ialog boxes can be used to input data and output results "ata can be read from and written to files "ata can be formatted using the !tring method format

:;

:<

:=

;>

You might also like