/** * The Election class models an electronic voting system. Election * instances can support elections with any number of candidates, * though the number is fixed once an Election object is created. * After the candidates' names have been added, users vote by invoking * the vote() method and passing in the number of the candidate they * wish to vote for. Once the election is over, the printResults() * method finds the winner and displays the results. * * @author Brad Richards * @version 1.0 */ public class Election { private String[] candidates; // Array of candidate names private int[] votes; // Total votes for each candidate private boolean votingStarted; // Has voting started yet? /** * The constructor for our Election class. * * @param numCandidates The number of candidates expected for * this election. */ public Election(int numCandidates) { candidates = new String[numCandidates]; votes = new int[numCandidates]; votingStarted = false; } /** * Allows the user to add candidates to the election (or replace * existing candidates with new ones). * * @param name The name of the candidate to be added. * @param index Desired position within candidate list (1-based) */ public void addCandidate(String name, int index) { if (votingStarted) { System.out.println("Hey -- you can't change candidates after voting starts!"); } else if (index > 0 && index <= candidates.length) { candidates[index-1] = name; } } /** * Prints the names of the candidates, in order. */ public void printCandidates() { for(int i=0; i 0 && index <= votes.length){ votes[index-1] = votes[index-1] + 1; } } /** * Finds the winner of the election and prints their name and the * number of votes they received. In the case of a tie, the candidate * earliest in the list is given the win. It finds the winner by * keeping track of the position of the largest vote count. * This index can be used to retrieve both the candidate's name and * the number of votes they got. */ public void printResults() { int idxOfMax = 0; // Position of largest total so far for(int i=1; i votes[idxOfMax]) { idxOfMax = i; } } // After inspecting each of the vote counters, we know who won. // Don't forget to adjust zero-based array index to 1-based // candidate number. System.out.println("The winner is candidate "+(idxOfMax+1)+", "+ candidates[idxOfMax]+", with "+votes[idxOfMax]+ " votes."); } }