Java Reference
In-Depth Information
The data in the first row of these three arrays correspond to the candidate whose
name is stored in the first row of the array candidatesName , and so on. In the
voting-by-region array, column 1 corresponds to Region 1, column 2 corresponds to
Region 2, and so on. Recall that, in Java, an array index starts at 0 . Therefore, if the
name of this array in the program is, say, votesByRegion , votesByRegion[][0]
refers to the first column and thus Region 1, and so on.
For easy reference, for the remainder of this discussion, assume that in the program
we are writing, the name of the candidates' name array is candidatesName , the
name of the voting-by-region array is votesByRegion , and the name of the array
containing the total votes is totalVotes .
The first thing we must do in this program is read the candidates' names from the
input file candData.txt into the array candidatesName . Once the candidates'
names are stored in the array candidatesName , we must sort this array.
Next, we process the voting data. Every entry in the file voteData.txt contains
candidatesName , regionNumber , and numberOfVotesForTheCandidate .To
process this entry, we find the appropriate entry in the array votesByRegion and
update this entry by adding numberOfVotesForTheCandidate to this entry. There-
fore, it follows that the array votesByRegion must be initialized to zero. Processing
the voting data is described in detail later in this section.
After processing the voting data, the next step is to calculate the total votes received
by each candidate. This is accomplished by adding the votes received in each region.
Therefore, we must initialize the array totalVotes to zero. Finally, we output the
results as shown earlier.
This discussion translates into the following algorithm:
1. Read the candidates' names into the array candidatesName .
2. Sort the array candidatesName .
3. Process the voting data.
4. Calculate the total votes received by each candidate.
5. Output the results as shown earlier.
Note that the arrays votesByRegion and totalVotes are automatically initialized
when they are created. Because the input data is provided in two separate files, in this
program, we must open two input files. We open both input files in the method main .
To implement the preceding five steps, the program consists of several methods,
which are described next.
1
4
This method reads the data from the input file candData.txt and fills the array
candidatesName . The input file is opened in the method main . Note that this
method has two parameters: a parameter corresponding to the input file and
Method
getCandidates
Name
Search WWH ::




Custom Search