// Yazzy Latif // 07/15/2020 // CSE 142 // TA: Grace Hopper // Election Good Example // A program to read in the number of votes each of two candidates received // in a number of precincts, then compute the winner of the election. // /* DEVELOPMENT NOTES: ((Note: this is not something you should include in your own programs; this is included here to aid in your understanding and to provide additional context for the program.)) This is a BAD version of the program that has lots of redundancy and very little structure. */ import java.util.*; public class ElectionRedundant { public static final int NUM_VOTERS = 807; public static void main(String[] args) { Scanner console = new Scanner(System.in); intro(); System.out.println("Enter Pizza Party candidate's totals:"); System.out.print("How many precincts? "); int numPrecincts = console.nextInt(); int pizza = 0; for (int i = 1; i <= numPrecincts; i++) { System.out.print(" Votes in next precinct? "); int votes = console.nextInt(); pizza += votes; } System.out.println(); System.out.println("Enter Pajama Party candidate's totals:"); System.out.print("How many precincts? "); numPrecincts = console.nextInt(); int pajama = 0; for (int i = 1; i <= numPrecincts; i++) { System.out.print(" Votes in next precinct? "); int votes = console.nextInt(); pajama += votes; } System.out.println(); int totalVotes = pizza + pajama; double pct1 = 100.0 * pizza / totalVotes; double pct2 = 100.0 * pajama / totalVotes; if (pct1 > pct2) { System.out.println("Pizza Party received " + round2(pct1) + "% of the votes cast"); System.out.println("Pajama Party received " + round2(pct2) + "% of the votes cast"); System.out.println("Pizza Party wins!"); double turnoutPct = 100.0 * totalVotes / NUM_VOTERS; System.out.println("Turnout was " + round2(turnoutPct) + "%"); } else if (pct2 > pct1) { System.out.println("Pizza Party received " + round2(pct1) + "% of the votes cast"); System.out.println("Pajama Party received " + round2(pct2) + "% of the votes cast"); System.out.println("Pajama Party wins!"); double turnoutPct = 100.0 * totalVotes / NUM_VOTERS; System.out.println("Turnout was " + round2(turnoutPct) + "%"); } else { System.out.println("Pizza Party received " + round2(pct1) + "% of the votes cast"); System.out.println("Pajama Party received " + round2(pct2) + "% of the votes cast"); System.out.println("It's a tie!"); double turnoutPct = 100.0 * totalVotes / NUM_VOTERS; System.out.println("Turnout was " + round2(turnoutPct) + "%"); } } // Prints out an introduction to the program. public static void intro() { System.out.println("This program reads in data for two candidates"); System.out.println("and computes the result of an election"); System.out.println(); } // Returns the given number rounded to two decimal places. // // double num - the number to round public static double round2(double num) { return Math.round(num * 100.0) / 100.0; } }