Chapter 3 Introduction to Objects and InputOutput Java

Chapter 3: Introduction to Objects and Input/Output Java Programming: From Problem Analysis to Program Design, Second Edition Java Programming: From Problem Analysis to Program Design,

Chapter Objectives s Learn about objects and reference variables. s Explore how to use predefined methods in a program. s Become familiar with the class String. s Learn how to use input and output dialog boxes in a program. Java Programming: From Problem Analysis to Program Design, Second Edition 2

Chapter Objectives s Explore how to format the output of decimal numbers with the String method format. s Become familiar with file input and output. Java Programming: From Problem Analysis to Program Design, Second Edition 3

Object and Reference Variables s Declare a reference variable of a class type. s Allocate memory space for data. s Instantiate an object of that class type. s Store the address of the object in a reference variable. Java Programming: From Problem Analysis to Program Design, Second Edition 4

Object and Reference Variables int x; String str; x = 45; str = "Java Programming"; //Line 1 2 3 4 Java Programming: From Problem Analysis to Program Design, Second Edition 5

Object and Reference Variables String str; str = "Hello there!"; Java Programming: From Problem Analysis to Program Design, Second Edition 6

Object and Reference Variables s Primitive type variables directly store data into their memory space. s Reference variables store the address of the object containing the data. s An object is an instance of a class and the operator new is used to instantiate an object. Java Programming: From Problem Analysis to Program Design, Second Edition 7

Using Predefined Classes and Methods in a Program s There are many predefined packages, classes, and methods in Java. s Library: A collection of packages. s Package: Contains several classes. s Class: Contains several methods. s Method: A set of instructions. Java Programming: From Problem Analysis to Program Design, Second Edition 8

Using Predefined Classes and Methods in a Program To use a method you must know: s Name of the class containing the method (Math). s Name of the package containing the class (java. lang). s Name of the method - (pow), its has two parameters s Math. pow(x, y) = xy Java Programming: From Problem Analysis to Program Design, Second Edition 9

Using Predefined Classes and Methods in a Program s Example method call: import java. lang; //imports package Math. pow(2, 3); //calls power method // in class Math s Dot (. )operator: Used to access the method in the class. Java Programming: From Problem Analysis to Program Design, Second Edition 10

The class String variables are reference variables. s Given: String name; s Equivalent statements: name = new String("Lisa Johnson"); name = "Lisa Johnson"; Java Programming: From Problem Analysis to Program Design, Second Edition 11

The class String s A String object is an instance of class String. s A String object with the value "Lisa Johnson" is instantiated. s The address of the object is stored in name. s The new operator is unnecessary when instantiating Java strings. s String methods are called using the dot operator. Java Programming: From Problem Analysis to Program Design, Second Edition 12

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition 13

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition 14

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition 15

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition 16

Input/Output s Input data s Format output s Output results s Format output s Read from and write to files Java Programming: From Problem Analysis to Program Design, Second Edition 17

Formatting Output with printf s The syntax to use the method printf to produce output on the standard output device is: System. out. printf(format. String); or System. out. printf(format. String, argument. List); s format. String is a string specifying the format of the output and argument. List is a list of arguments. s argument. List is a list of arguments that consists of constant values, variables, or expressions. s If there is more than one argument in argument. List, the arguments are separated with commas. Java Programming: From Problem Analysis to Program Design, Second Edition 18

Formatting Output with printf System. out. printf("Hello there!"); Consists of only the format string and the statement: System. out. printf("There are %. 2 f inches in %d centimeters. %n", centimeters / 2. 54, centimeters); s Consists of both the format string and argument. List. s %. 2 f and %d are called format specifiers. s By default, there is a one-to-one correspondence between format specifiers and the arguments in argument. List. s The first format specifier, %. 2 f, is matched with the first argument, which is the expression centimeters / 2. 54. s The second format specifier, %d, is matched with the second argument, which is centimeters. s The format specifier %n positions the insertion point at the beginning of the next line. Java Programming: From Problem Analysis to Program Design, Second Edition 19

Formatting Output with printf s A format specifier for general, character, and numeric types has the following syntax: %[argument_index$][flags][width][. precision]conversion s The expressions in square brackets are optional. That is, they may or may not appear in a format specifier. s 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. s The optional flags is a set of characters that modify the output format. s The optional width is a (decimal) integer that indicates the minimum number of characters to be written to the output. s The optional precision is a (decimal) integer that is usually used to restrict the number of characters. s The required conversion is a character that indicates how the argument should be formatted. Java Programming: From Problem Analysis to Program Design, Second Edition 20

Formatting Output with printf Java Programming: From Problem Analysis to Program Design, Second Edition 21

Parsing Numeric Strings s A string consisting of only integers or decimal numbers is called a numeric string. s To convert a string consisting of an integer to a value of the type int, we use the following expression: Integer. parse. Int(str. Expression) Integer. parse. Int("6723") = 6723 Integer. parse. Int("-823") = -823 Java Programming: From Problem Analysis to Program Design, Second Edition 22

Parsing Numeric Strings s To convert a string consisting of a decimal number to a value of the type float, we use the following expression: Float. parse. Float(str. Expression) Float. parse. Float("34. 56") = 34. 56 Float. parse. Float("-542. 97") = -542. 97 s To convert a string consisting of a decimal number to a value of the type double, we use the following expression: Double. parse. Double(str. Expression) Double. parse. Double("345. 78") = 345. 78 Double. parse. Double("-782. 873") = -782. 873 Java Programming: From Problem Analysis to Program Design, Second Edition 23

Parsing Numeric Strings s s Integer, Float, and Double are classes designed to convert a numeric string into a number. These classes are called wrapper classes. parse. Int is a method of the class Integer, which converts a numeric integer string into a value of the type int. parse. Float is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float. parse. Double is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double. Java Programming: From Problem Analysis to Program Design, Second Edition 24

Using Dialog Boxes for Input/Output s Use a graphical user interface (GUI). s class JOption. Pane s Contained in package javax. swing. s Contains methods show. Input. Dialog and show. Message. Dialog. s Syntax: str = JOption. Pane. show. Input. Dialog(str. Expression) s Program must end with System. exit(0); Java Programming: From Problem Analysis to Program Design, Second Edition 25

Parameters for the Method show. Message. Dialog Java Programming: From Problem Analysis to Program Design, Second Edition 26

JOption. Pane Options for the Parameter message. Type Java Programming: From Problem Analysis to Program Design, Second Edition 27

JOption. Pane Example Java Programming: From Problem Analysis to Program Design, Second Edition 28

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; Java Programming: From Problem Analysis to Program Design, Second Edition 29

File Input/Output s File: An area in secondary storage used to hold information. s 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. s We make use of the class File. Reader. Java Programming: From Problem Analysis to Program Design, Second Edition 30

File Input/Output s s 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 in. File and initializes it to the file prog. dat: Scanner in. File = new Scanner (new File. Reader("a: \prog. dat")); You use the object in. File 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, next. Int, next. Double, and so on. Java Programming: From Problem Analysis to Program Design, Second Edition 31

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. Java Programming: From Problem Analysis to Program Design, Second Edition 32

File Input/Output Example 3 -16 Suppose an input file, say employee. Data. txt, consists of the following data: Emily Johnson 45 13. 50 Scanner in. File = new Scanner (new File. Reader("a: \employee. Data. txt")); String first. Name; String last. Name; double hours. Worked; double pay. Rate; double wages; first. Name = in. File. next(); last. Name = in. File. next(); hours. Worked = in. File. next. Double(); pay. Rate = in. File. next. Double(); wages = hours. Worked * pay. Rate; in. File. close(); //close the input file Java Programming: From Problem Analysis to Program Design, Second Edition 33

Storing (Writing) Output in a File s To store the output of a program in a file, you use the class Print. Writer. s Declare a Print. Writer variable and associate this variable with the destination. s Suppose the output is to be stored in the file prog. out on floppy disk A. s Consider the following statement: Print. Writer out. File = new Print. Writer("a: \prog. out"); s This statement creates the Print. Writer object out. File and associates it with the file prog. out on floppy disk A. s You can now use the methods print, println, printf, and flush with out. File in the same way they have been used with the object System. out. Java Programming: From Problem Analysis to Program Design, Second Edition 34

Storing (Writing) Output in a File s The statement: out. File. 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. s Step 4 requires closing the file. You close the input and output files by using the method close. in. File. close(); out. File. close(); s 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. Java Programming: From Problem Analysis to Program Design, Second Edition 35

Storing (Writing) Output in a File (throws clause) s During program execution, various things can happen; for example, division by zero or inputting a letter for a number. s In such cases, we say that an exception has occurred. s If an exception occurs in a method, then the method should either handle the exception or throw it for the calling environment to handle. s If an input file does not exist, the program throws a File. Not. Found. Exception. s If an output file cannot be created or accessed, the program throws a File. Not. Found. Exception. s For the next few chapters, we will simply throw the exceptions. s Because we do not need the method main to handle the File. Not. Found. Exception exception, we will include a command in the heading of the method main to throw the File. Not. Found. Exception exception. Java Programming: From Problem Analysis to Program Design, Second Edition 36

Skeleton of I/O Program Java Programming: From Problem Analysis to Program Design, Second Edition 37

Programming Example: Movie Ticket Sale and Donation to Charity s 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. s Output: Java Programming: From Problem Analysis to Program Design, Second Edition 38

Programming Example: Movie Ticket Sale and Donation to Charity 1. Import appropriate packages. 2. Get inputs from user using JOption. Pane. show. Input. Dialog. 3. Perform appropriate calculations. 4. Display output using JOption. Pane. show. Message. Dialog. Java Programming: From Problem Analysis to Program Design, Second Edition 39

Programming Example: Student Grade s Input: File containing student’s first name, last name, five test scores. s Output: File containing student’s first name, last name, five test scores, average of five test scores. Java Programming: From Problem Analysis to Program Design, Second Edition 40

Programming Example: Student Grade 1. Import appropriate packages. 2. Get input from file using the classes Scanner and File. Reader. 3. Read and calculate the average of test scores. 4. Write to output file using the class Print. Writer. 5. Close files. Java Programming: From Problem Analysis to Program Design, Second Edition 41

Chapter Summary s Primitive type variables store data into their memory space. s Reference variables store the address of the object containing the data. s An object is an instance of a class. s Operator new is used to instantiate an object. s Garbage collection reclaims memory that is not being used. Java Programming: From Problem Analysis to Program Design, Second Edition 42

Chapter Summary s To use a predefined method, you must know its name and the class and package it belongs to. s The dot (. ) operator is used to access a certain method in a class. s Methods of the class String are used to manipulate input and output data. s Dialog boxes can be used to input data and output results. s Data can be read from and written to files. s Data can be formatted using the String method format. Java Programming: From Problem Analysis to Program Design, Second Edition 43
- Slides: 43