Wrap-Up

Answers to Self Review Exercises

14.1

a) ones, zeros. b) bit. c) file. d) characters. e) database. f) System.err. g) readInt. h) seek.

14.2
  1. False. These three streams are created for the programmer when a Java application begins executing.
  2. True.
  3. True.
  4. True.
  5. False. Text files are human readable.
  6. True.
  7. False. Class Formatter contains method format, which enables formatted data to be output to the screen or to a file.
14.3
  1. Scanner inOldMaster =new Scanner( new File ( "oldmast.txt" ) );
  2. Scanner inTransaction = new Scanner( new File( "trans.txt" ) );
  3. Formatter outNewMaster = new Formatter( "newmast.txt" );
  4. AccountRecord account = new AccountRecord(); account.setAccount( inOldMaster.nextInt() ); account.setFirstName( inOldMaster.next() ); account.setLastName( inOldMaster.next() ); account.setBalance( inOldMaster.nextDouble() );
  5. TransactionRecord transaction = new Transaction(); transaction.setAccount( inTransaction.nextInt() ); transaction.setAmount( inTransaction.nextDouble() );
  6. outNewMaster.format( "%d %s %s %.2f ", account.getAccount(), account.getFirstName(), account.getLastName(), account.getBalance() );
14.4
  1. ObjectInputStream inOldMaster = new ObjectInputStream( new FileInputStream( "oldmast.ser" ) );
  2. ObjectInputStream inTransaction = new ObjectInputStream( new FileInputStream( "trans.ser" ) );
  3. ObjectOutputStream outNewMaster = new ObjectOutputStream( new FileOutputStream( "newmast.ser" ) );
  4. accountRecord = ( AccountRecordSerializable ) inOldMaster.readObject();
  5. transactionRecord = ( TransactionRecord ) inTransaction.readObject();
  6. outNewMaster.writeObject( newAccountRecord );
14.5
  1. Error: The file has not been opened before the attempt is made to output data to the stream.

    Correction: Open a file for output by creating a new ObjectOutputStream object that wraps a FileOutputStream object.

  2. Error: This example uses text files with a Scanner, there is no object serialization. As a result, method readObject cannot be used to read that data from the file. Each piece of data must be read separately, then used to create a PayablesRecord object.

    Correction: Use methods of inPayable to read each piece of the PayablesRecord object.

Exercises

14.6

Fill in the blanks in each of the following statements:

  1. Computers store large amounts of data on secondary storage devices as __________.
  2. A(n) __________ is composed of several fields.
  3. To facilitate the retrieval of specific records from a file, one field in each record is chosen as a(n) __________.
  4. Files that are created using byte-based streams are referred to as __________ files, while files created using character-based streams are referred to as __________ files.
  5. The standard stream objects are __________, __________ and __________.
14.7

Determine which of the following statements are true and which are false. If false, explain why.

  1. The impressive functions performed by computers essentially involve the manipulation of zeros and ones.
  2. People specify programs and data items as characters. Computers then manipulate and process these characters as groups of zeros and ones.
  3. Data items represented in computers form a data hierarchy in which data items become larger and more complex as we progress from fields to characters to bits and so on.
  4. A record key identifies a record as belonging to a particular field.
  5. Companies store all their information in a single file to facilitate computer processing of the information. When a program creates a file, the file is retained by the computer for future reference.
14.8

(File Matching) Self-Review Exercise 14.3 asks the reader to write a series of single statements. Actually, these statements form the core of an important type of file-processing program, namely, a file-matching program. In commercial data processing, it is common to have several files in each application system. In an accounts receivable system, for example, there is generally a master file containing detailed information about each customer, such as the customer's name, address, telephone number, outstanding balance, credit limit, discount terms, contract arrangements and possibly a condensed history of recent purchases and cash payments.

As transactions occur (i.e., sales are made and payments arrive in the mail), information about them is entered into a file. At the end of each business period (a month for some companies, a week for others, and a day in some cases), the file of transactions (called "trans.txt" ) is applied to the master file (called "oldmast.txt" ) to update each account's purchase and payment record. During an update, the master file is rewritten as the file "newmast.txt", which is then used at the end of the next business period to begin the updating process again.

File-matching programs must deal with certain problems that do not arise in single-file programs. For example, a match does not always occur. If a customer on the master file has not made any purchases or cash payments in the current business period, no record for this customer will appear on the transaction file. Similarly, a customer who did make some purchases or cash payments could have just moved to this community, and if so, the company may not have had a chance to create a master record for this customer.

Write a complete file-matching accounts receivable program. Use the account number on each file as the record key for matching purposes. Assume that each file is a sequential text file with records stored in increasing account-number order.

  1. Define class TRansactionRecord. Objects of this class contain an account number and amount for the transaction. Provide methods to modify and retrieve these values.
  2. Modify class AccountRecord in Fig. 14.6 to include method combine, which takes a transactionRecord object and combines the balance of the AccountRecord object and the amount value of the transactionRecord object.
  3. Write a program to create data for testing the program. Use the sample account data in Fig. 14.39 and Fig. 14.40. Run the program to create the files TRans.txt and oldmast.txt, to be used by your file-matching program.

    Figure 14.39. Sample data for master file.

    Master file Account number

    Name

    Balance

    100

    Alan Jones

    348.17

    300

    Mary Smith

    27.19

    500

    Sam Sharp

    0.00

    700

    Suzy Green

    14.22

     

    Figure 14.40. Sample data for transaction file.

    Transaction file Account number

    Transaction amount

    100

    27.14

    300

    62.11

    400

    100.56

    900

    82.17

     
  4. Create class FileMatch to perform the file-matching functionality. The class should contain methods that read oldmast.txt and TRans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.) When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
14.9

(File Matching with Multiple Transactions) It is possible (and actually common) to have several transaction records with the same record key. This situation occurs, for example, when a customer makes several purchases and cash payments during a business period. Rewrite your accounts receivable file-matching program from Exercise 14.8 to provide for the possibility of handling several transaction records with the same record key. Modify the test data of CreateData.java to include the additional transaction records in Fig. 14.41.

Figure 14.41. Additional transaction records.

Account number

Dollar amount

300

83.89

700

80.78

700

1.53

14.10

(File Matching with Object Serialization) Recreate your solution for Exercise 14.9 using object serialization. Use the statements from Exercise 14.4 as your basis for this program. You may want to create applications to read the data stored in the .ser filesthe code in Section 14.7.3 can be modified for this purpose.

14.11

(Hardware Store Inventory) You are the owner of a hardware store and need to keep an inventory that can tell you what different tools you stock, how many of each you have on hand and the cost of each one. Write a program that initializes the random-access file "hardware.dat" to 100 empty records and lets you input the data concerning each tool, list all your tools, delete a record for a tool that you no longer have and update any information in the file. The tool identification number should be the record number. Use the information in Fig. 14.42 to start your file.

Figure 14.42. Data for Exercise 14.11.

Record number

Tool name

Quantity

Cost

3

Sander

18

35.99

19

Hammer

128

10.00

26

Jigsaw

16

14.25

39

Mower

10

79.50

56

Saw

8

89.99

76

Screwdriver

236

4.99

81

Sledgehammer

32

19.75

88

Wrench

65

6.48

 
14.12

(Telephone-Number Word Generator) Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them (Fig. 14.43). Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in Fig. 14.43 to develop the seven-letter word "NUMBERS." Every seven-letter word corresponds to exactly one seven-digit telephone number. A restaurant wishing to increase its takeout business could surely do so with the number 825-3688 (i.e., "TAKEOUT").

Figure 14.43. Telephone keypad digits and letters.

Digit

Letters

2

A B C

3

D E F

4

G H I

5

J K L

6

M N O

7

P R S

8

T U V

9

W X Y

 

Every seven-letter phone number corresponds to many different seven-letter words. Unfortunately, most of these words represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a barbershop would be pleased to know that the shop's telephone number, 424-7288, corresponds to "HAIRCUT." The owner of a liquor store would, no doubt, be delighted to find that the store's number, 233-7226, corresponds to "BEERCAN." A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters "PETCARE." An automotive dealership would be pleased to know that the dealership number, 639-2277, corresponds to "NEWCARS."

Write a program that, given a seven-digit number, uses a PrintStream object to write to a file every possible seven-letter word combination corresponding to that number. There are 2,187 (37) such combinations. Avoid phone numbers with the digits 0 and 1.

14.13

(Student Poll) Figure 7.8 contains an array of survey responses that is hard coded into the program. Suppose we wish to process survey results that are stored in a file. This exercise requires two separate programs. First, create an application that prompts the user for survey responses and outputs each response to a file. Use a Formatter to create a file called numbers.txt. Each integer should be written using method format. Then modify the program in Fig. 7.8 to read the survey responses from numbers.txt. The responses should be read from the file by using a Scanner. Method nextInt should be used to input one integer at a time from the file. The program should continue to read responses until it reaches the end of file. The results should be output to the text file "output.txt".

14.14

Modify Exercise 11.18 to allow the user to save a drawing into a file or load a prior drawing from a file using object serialization. Add buttons Load (to read objects from a file), Save (to write objects to a file) and Generate Shapes (to display a random set of shapes on the screen). Use an ObjectOutputStream to write to the file and an ObjectInputStream to read from the file. Write the array of MyShape objects using method writeObject (class ObjectOutputStream), and read the array using method readObject (ObjectInputStream). Note that the object-serialization mechanism can read or write entire arraysit is not necessary to manipulate each element of the array of MyShape objects individually. It is simply required that all the shapes be Serializable. For both the Load and Save buttons, use a JFileChooser to allow the user to select the file in which the shapes will be stored or from which they will be read. When the user first runs the program, no shapes should be displayed on the screen. The user can display shapes by opening a previously saved file of shapes or by clicking the Generate Shapes button. When the Generate Shapes button is clicked, the application should generate a random number of shapes up to a total of 15. Once there are shapes on the screen, users can save them to a file using the Save button.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net