Java Reference
In-Depth Information
It now follows that the method
main
needs (at least) the following variables:
int
lineCount = 0;
//variable to store the line count
int
[] letterCount =
new
int[26];
//array to store the letter
//count
int
next;
//variable to read a character
FileReader inputStream =
new
FileReader("text.txt");
PrintWriter outfile =
new
PrintWriter("textCh.out");
(Note that the method
read
throws an
IOException
when something goes wrong.
At this point, we will ignore this exception by throwing it in the program. Excep-
tions are covered in detail in Chapter 11.)
In this declaration,
letterCount[0]
stores the
A
count,
letterCount[1]
stores the
B
count, and so on. Clearly, the variable
lineCount
and the array
letterCount
must be initialized to
0
.
The algorithm for the program is:
1. Declare and initialize the variables.
2. Create objects to open the input and output files.
3. While there is more data in the input file:
a. For each character in a line:
i. Read and write the character.
ii. Increment the appropriate letter count.
b. Increment the line count.
4. Output the line count and letter counts.
5. Close the files.
To simplify the method
main
, we divide it into three methods:
1. Method
copyText
2. Method
chCount
3. Method
writeTotal
The following sections describe each method in detail. Then, with the help of these
methods, we describe the algorithm for the method
main
.
9
This method reads a line and outputs the line. Whenever a nonblank character is
found, it calls the method
chCount
to update the letter count. Clearly, this method
has four parameters: an input stream object, an output stream object, a variable to
read the character, and the array to update the letter count.
copyText
Search WWH ::
Custom Search