Java Reference
In-Depth Information
Input:
A file containing the text to be processed.
Output:
A file containing the text, number of lines, and the number of times a letter
appears in the text.
Based on the desired output, it is clear that we must output the text as is. That is, if
the text contains any whitespace characters, they must be output as well.
Let's first describe the variables that are necessary to develop the program. This will
simplify the discussion that follows.
PROBLEM
ANALYSIS
AND
ALGORITHM
DESIGN
Variables
We need to store the letter count and the line count. Therefore, we need a variable
to store the line count and 26 variables to store the letter count. We will use an array
of 26 elements to perform the letter count. We also need a variable to read and store
each character in turn, because the input file will be read character-by-character.
Because the data will be read from an input file and the output will be saved in a file,
we need an input stream object to open the input file and an output stream object to
open the output file. Because the program needs to do a character count, the program
should read the input file character-by-character. Moreover, the program should also
count the number of lines. Therefore, while reading the data from the input file, the
program must capture the newline character. The
Scanner
class
does not contain
any method that can only read the next character in the input stream, unless the
character is delimited by whitespace characters such as blanks. Moreover, using the
Scanner
class
, the program should read the entire line or else the newline
character will be ignored.
To simplify the character-by-character reading of the input file, we use the Java
class
FileReader
. (In Chapter 3, we introduced this class to create and initialize a
Scanner
object to the input source.) The
class
FileReader
contains the method
read
that returns the integer value of the next character. For example, if the next
input character is
A
, the method
read
returns
65
. We can use the cast operator to
change the value
65
to the character
A
. Notice that the method
read
does not skip
whitespace characters. Also, the method
read
returns
-1
when the end of the input
file has been reached. We can, therefore, use the value returned by the method
read
to determine whether the end of the input file is reached.
Consider the following statement:
FileReader inputStream =
new
FileReader("text.txt");
This statement creates the
FileReader
object
inputStream
and initializes it to the
input file
text.txt
.If
nextChar
is a
char
variable, then the following statement
reads and stores the next character from the input file into
nextChar
:
ch = (
char
) inputStream.read();
Search WWH ::
Custom Search