Java Reference
In-Depth Information
We need to store the names of the seven candidates and the score obtained by each. We
could
use a
String
array
for the names and an
int
array for the scores. But what if we needed to store many more attributes of a candidate? For
each attribute, we would need to add another array of the appropriate type. To cater for this possibility and to make
our program more flexible, we will create a class
Person
and use an array of
Person
.
What will this
Person
class look like? For our problem, it will have two instance fields,
name
and
numVotes
, say.
We define it as follows:
class Person {
String name;
int numVotes;
Person(String s, int n) {
name = s;
numVotes = n;
}
} //end class Person
To cater for seven candidates, we set the symbolic constant
MaxCandidates
to
7
and declare the
Person
array
candidate
as follows:
Person[] candidate = new Person[MaxCandidates+1];
We will use
candidate[h]
to store information for candidate
h
,
h
=
1
,
7
; we will not use
candidate[0]
. This will
enable us to process the votes more naturally than if we had used
candidate[0]
. For example, if there is a vote for
candidate 4, we want to increment the vote count for
candidate[4]
. If we had used
candidate[0]
to store information
for the first candidate, we would have had to increment the count for
candidate[3]
, given a vote of 4. This can be
misleading and disconcerting.
Suppose
in
is declared as follows:
Scanner in = new Scanner(new FileReader("votes.txt"));
We will read the names and set the scores to 0 with the following code:
for (int h = 1; h <= MaxCandidates; h++)
candidate[h] = new Person(in.nextLine(), 0);
When this code is executed, we can picture
candidate
as shown in Figure
2-11
. Remember, we are not using
candidate[0]
.
Search WWH ::
Custom Search