Java Reference
In-Depth Information
name: Nirvan Singh
numVotes: 0
name: Denise Duncan
numVotes: 0
candidate[1]
candidate[2]
candidate[3]
candidate[4]
candidate[5]
candidate[6]
candidate[7]
name: Joshua Regrello
numVotes: 0
name: Torrique Granger
numVotes: 0
name:Saskia Kalicharan
numVotes: 0
name: Dawren Greenidge
numVotes: 0
name: Jordon Cato
numVotes: 0
Figure 2-11. Array candidate after reading the names and setting the scores to 0
Next, we must process the votes. We will delegate this to the function processVotes . This will read each vote and
add 1 to the score for the appropriate candidate. Thus, if the vote is 5, it must add 1 to the score for candidate 5.
Another task of this function is to count the number of valid and spoiled votes and return these values to main .
But how does a function return more than one value? Well, it can return one value—an object—and this object can
contain many fields.
In this example, we can declare a class ( VoteCount , say) with two fields and a constructor, like this:
class VoteCount {
int valid, spoilt;
VoteCount(int v, int s) {
valid = v;
spoilt = s;
}
}
The following statement will create an object called votes and set votes.valid and votes.spoilt to 0 .
VoteCount votes = new VoteCount(0, 0);
We could also have dispensed with the constructor and created the object with this statement:
VoteCount votes = new VoteCount();
Search WWH ::




Custom Search