AhmadLang / Java, How To Program, 2004
.pdf
a.Write a statement that opens file "oldmast.ser" for inputuse ObjectInputStream variable inOldMaster to wrap a FileInputStream object.
[Page 738]
b.Write a statement that opens file "trans.ser" for inputuse ObjectInputStream variable inTransaction to wrap a FileInputStream object.
c.Write a statement that opens file "newmast.ser" for output (and creation)use
ObjectOutputStream variable outNewMaster to wrap a FileOutputStream.
d.Write a statement that reads a record from the file "oldmast.ser". The record is an object of class AccountRecordSerializableuse ObjectInputStream variable inOldMaster. Assume class AccountRecordSerializable is the same as the AccountRecordSerializable class in Fig.
14.17
e.Write a statement that reads a record from the file "trans.ser". The record is an object of class transactionRecorduse ObjectInputStream variable inTransaction.
f.Write a statement that outputs a record to the file "newmast.ser". The record is an object of type AccountRecordSerializableuse ObjectOutputStream variable outNewMaster.
14.5 Find the error in each block of code and show how to correct it.
a. Assume that account, company and amount are declared.
ObjectOutputStream outputStream;
outputStream.writeInt( account ); outputStream.writeChars( company ); outputStream.writeDouble( amount );
b.The following statements should read a record from the file "payables.txt". The Scanner variable inPayable should be used to refer to this file.
Scanner inPayable = new Scanner( new File( "payables.txt" ) ); PayablesRecord record = ( PayablesRecord ) inPayable.readObject();
[Page 738 (continued)]
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 a. False. These three streams are created for the programmer when a Java application begins executing.
b.True.
c.True.
d.True.
e.False. Text files are human readable.
f.True.
g.False. Class Formatter contains method format, which enables formatted data to be output to the screen or to a file.
14.3 |
a. |
Scanner |
inOldMaster =new Scanner( new |
File ( "oldmast.txt" |
) |
); |
|
b. |
Scanner |
inTransaction = new Scanner( |
new File( "trans.txt" |
) |
); |
c.Formatter outNewMaster = new Formatter( "newmast.txt" );
d.AccountRecord account = new AccountRecord();
account.setAccount( inOldMaster.nextInt() ); account.setFirstName( inOldMaster.next() ); account.setLastName( inOldMaster.next() ); account.setBalance( inOldMaster.nextDouble() );
e. TransactionRecord transaction = new Transaction(); transaction.setAccount( inTransaction.nextInt() ); transaction.setAmount( inTransaction.nextDouble() );
[Page 739]
f. outNewMaster.format( "%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(), account.getBalance() );
14.4 a. ObjectInputStream inOldMaster = new ObjectInputStream( new FileInputStream( "oldmast.ser" ) );
b.ObjectInputStream inTransaction = new ObjectInputStream( new FileInputStream( "trans.ser" ) );
c.ObjectOutputStream outNewMaster = new ObjectOutputStream( new FileOutputStream( "newmast.ser" ) );
d.accountRecord = ( AccountRecordSerializable ) inOldMaster.readObject();
e.transactionRecord = ( TransactionRecord ) inTransaction.readObject();
f.outNewMaster.writeObject( newAccountRecord );
14.5 a. 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.
b.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.
[Page 739 (continued)]
Exercises
14.6Fill in the blanks in each of the following statements:
a.Computers store large amounts of data on secondary storage devices as
__________.
b.A(n) __________ is composed of several fields.
c.To facilitate the retrieval of specific records from a file, one field in each record is chosen as a(n) __________.
d.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.
e.The standard stream objects are __________, __________ and __________.
14.7Determine which of the following statements are true and which are false. If false, explain why.
a.The impressive functions performed by computers essentially involve the manipulation of zeros and ones.
b.People specify programs and data items as characters. Computers then manipulate and process these characters as groups of zeros and ones.
c.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.
d.A record key identifies a record as belonging to a particular field.
e.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 fileprocessing 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.
[Page 740]
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 singlefile 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
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 randomaccess 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 |
|
|
|
|
[Page 742]
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, 2337226, 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, 6392277, 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.14Modify 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.
[Page 743]
[Page 744]
Chapter 15. Recursion
It's a poor sort of memory that only works backwards.
Lewis Carroll, Alice in Wonderland
We must learn to explore all the options and possibilities that confront us in a complex and rapidly changing world.
James William Fulbright
Push onkeep moving.
Thomas Morton
O! thou hast damnable iteration, and art indeed able to corrupt a saint.
William Shakespeare
Life can only be understood backwards; but it must be lived forwards.
Soren Kierkegaard
OBJECTIVES
In this chapter you will learn:
The concept of recursion.
How to write and use recursive methods.
How to determine the base case and recursion step in a recursive algorithm.
How recursive method calls are handled by the system.
The differences between recursion and iteration, and when it is appropriate to use each.
[Page 745]
Outline
15.1 Introduction
15.2 Recursion Concepts
15.3 Example Using Recursion: Factorials
15.4 Example Using Recursion: Fibonacci Series
15.5 Recursion and the Method Call Stack
15.6 Recursion vs. Iteration
15.7 String Permutations
15.8 Towers of Hanoi
15.9 Fractals
