Java Reference
In-Depth Information
This
would
initialize the fields to
0
, but it is better to do so explicitly, like this:
votes.valid = votes.spoilt = 0;
When we read a valid vote,
++votes.valid
adds 1 to
votes.valid
, and when we read an invalid vote,
++votes.
spoilt
adds 1 to
votes.spoilt
. At the end, the function will return
votes
— an object containing the two counts.
Finally, we must write
printResults
, which prints the results in the format specified earlier. First we print the
total number of votes broken down into valid and spoiled votes. Then, using a
for
loop, we print the individual scores.
Next, it determines the winning score by calling
getLargest
to find the candidate whose
numVotes
field is the
largest. This is accomplished by these statements:
int win = getLargest(list, 1, MaxCandidates);
int winningVote = list[win].numVotes;
Here,
list
is the
Person
array. Using
winningVote
, it then makes another pass through the array looking for
candidates with this score. This ensures that if there are ties for the winner, all will be printed. Program P2.5 is the
complete solution for solving this voting problem.
Program P2.5
import java.util.*;
import java.io.*;
public class Voting {
final static int MaxCandidates = 7;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("votes.txt"));
PrintWriter out = new PrintWriter(new FileWriter("results.txt"));
Person[] candidate = new Person[MaxCandidates+1];
//get the names and set the scores to 0
for (int h = 1; h <= MaxCandidates; h++)
candidate[h] = new Person(in.nextLine(), 0);
VoteCount count = processVotes(candidate, MaxCandidates, in, out);
printResults(out, candidate, MaxCandidates, count);
in.close();
out.close();
} //end main
public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) {
VoteCount votes = new VoteCount(0, 0); //set valid, spoilt counts to 0
int v = in.nextInt();
while (v != 0) {
if (v < 1 || v > max) {
out.printf("Invalid vote: %d\n", v);
++votes.spoilt;
}
else {
++list[v].numVotes;
++votes.valid;
}
Search WWH ::
Custom Search