Java Reference
In-Depth Information
Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - Terminate program
? 3
Accounts with debit balances:
100 Bob Blue 24.98
500 Sue Yellow 224.62
Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - Terminate program
? 4
Fig. 15.8 | Credit-inquiry program. (Part 4 of 4.)
The record information is collected by reading through the file and determining if
each record satisfies the criteria for the selected account type. Line 18 in main calls method
getRequest (lines 41-68) to display the menu options, translates the number typed by the
user into a MenuOption and stores the result in MenuOption variable accountType . Lines
20-37 loop until the user specifies that the program should terminate. Lines 22-33 display
a header for the current set of records to be output to the screen. Line 35 calls method
readRecords (lines 71-97), which loops through the file and reads every record.
Method readRecords uses a try -with-resources statement (introduced in
Section 11.12) to create a Scanner that opens the file for reading (line 74)—recall that
try -with-resources will close its resource(s) when the try block terminates successfully or
due to an exception. The file will be opened for reading with a new Scanner object each
time readRecords is called, so that we can again read from the beginning of the file. Lines
78-81 read a record. Line 84 calls method shouldDisplay (lines 100-111) to determine
whether the current record satisfies the account type requested. If shouldDisplay returns
true , the program displays the account information. When the end-of-file marker is
reached, the loop terminates and the try -with-resources statement closes the Scanner and
the file. Once all the records have been read, control returns to main and getRequest is
again called (line 36) to retrieve the user's next menu option.
15.4.4 Updating Sequential-Access Files
The data in many sequential files cannot be modified without the risk of destroying other
data in the file. For example, if the name “ White ” needs to be changed to “ Worthington ,”
the old name cannot simply be overwritten, because the new name requires more space.
The record for White was written to the file as
300 Pam White 0.00
 
Search WWH ::




Custom Search