/****************************************************************************** * Name: Reference Solution * NetID: ref * Precept: P00 * * Description: Reads election data and prints the number of electoral votes * won by each candidate, along with the minimum number of * electoral votes needed to win the election. * * % java-introcs Election < 2012.txt * Romney 206 * Obama 332 * 270 needed to win * * % java-introcs Election < hogwarts.txt * Snape 26 * McGonagall 17 * 29 needed to win * ******************************************************************************/ public class Election { // returns the smallest integer strictly greater than 1/2 n // (assumes n is a non-negative integer) public static int majorityOf(int n) { return 1 + n/2; } public static void main(String[] args) { int candidateVotes1 = 0; // number of electoral votes int candidateVotes2 = 0; // for each candidate int totalElectoralVotes = 0; // total number of electoral votes // read the names of the two candidates String candidateName1 = StdIn.readString(); String candidateName2 = StdIn.readString(); // read the rest of the data file and compute statistics while (!StdIn.isEmpty()) { // read data for one region String state = StdIn.readString(); int electoralVotes = StdIn.readInt(); int votes1 = StdIn.readInt(); int votes2 = StdIn.readInt(); // update statistics totalElectoralVotes += electoralVotes; if (votes1 > votes2) candidateVotes1 += electoralVotes; else if (votes1 < votes2) candidateVotes2 += electoralVotes; } // print results StdOut.println(candidateName1 + " " + candidateVotes1); StdOut.println(candidateName2 + " " + candidateVotes2); StdOut.println(majorityOf(totalElectoralVotes) + " needed to win"); } }