Java Reference
In-Depth Information
Method
readRecords
(lines 37-59) reads and displays records from the file. Lines
39-40 display headers for the columns in the application's output. Lines 44-49 read and
display data from the file until the
end-of-file marker
is reached (in which case, method
hasNext
will return
false
at line 44). Lines 47-48 use
Scanner
methods
nextInt
,
next
and
nextDouble
to input an
int
(the account number), two
String
s (the first and last
names) and a
double
value (the balance). Each record is one line of data in the file. If the
information in the file is not properly formed (e.g., there's a last name where there should
be a balance), a
NoSuchElementException
occurs when the record is input. This exception
is handled in lines 51-54. If the
Scanner
was closed before the data was input, an
Ille-
galStateException
occurs (handled in lines 55-58). Note in the format string in line 47
that the account number, first name and last name are left justified, while the balance is
right justified and output with two digits of precision. Each iteration of the loop inputs
one line of text from the text file, which represents one record. Lines 62-66 define method
closeFile
, which closes the
Scanner
.
To retrieve data sequentially from a file, programs start from the beginning of the file and
read
all
the data consecutively until the desired information is found. It might be necessary
to process the file sequentially several times (from the beginning of the file) during the ex-
ecution of a program. Class
Scanner
does
not
allow repositioning to the beginning of the
file. If it's necessary to read the file again, the program must
close
the file and
reopen
it.
The program in Figs. 15.7-15.8 allows a credit manager to obtain lists of customers
with
zero balances
(i.e., customers who do not owe any money), customers with
credit bal-
ances
(i.e., customers to whom the company owes money) and customers with
debit bal-
ances
(i.e., customers who owe the company money for goods and services received). A
credit balance is a
negative
amount, a debit balance a
positive
amount.
MenuOption
enum
We begin by creating an
enum
type (Fig. 15.7) to define the different menu options the
credit manager will haveāthis is required if you need to provide specific values for the
enum
constants. The options and their values are listed in lines 7-10.
1
// Fig. 15.7: MenuOption.java
2
// enum type for the credit-inquiry program's options.
3
4
public
enum
MenuOption
5
{
6
// declare contents of enum type
7
ZERO_BALANCE(
1
),
8
CREDIT_BALANCE(
2
),
9
DEBIT_BALANCE(
3
),
10
END(
4
);
11
12
private
final
int
value;
// current menu option
13
Fig. 15.7
|
enum
type for the credit-inquiry program's menu options. (Part 1 of 2.)