Below is the syntax highlighted version of Ballot.java.
/*********************************************************************** * Name: COS 126 Staff * NetID: cos126 * Precept: P99 * * Ballot: represent a preferential ballot for RIRV * * Dependencies: Queue * * Note: there are MANY possible correct solutions! This is just one of them. */ public class Ballot { // instance variable: candidate list, favorite first private Queue<String> list; // constructor: make preferential ballot, ordered favorite to least public Ballot(String[] prefs) { list = new Queue<String>(); // favorite, at start of prefs, is the first one in for (int i = 0; i < prefs.length; i++) list.enqueue(prefs[i]); } // give string representation, most favorite in front public String toString() { // to help avoid extra > at start boolean first = true; // build the answer String result = ""; for (String name : list) { if (!first) result += " > "; else first = false; result += name; } return result; } // which remaining candidate is favorite? public String top() { // return the first name for (String name : list) return name; // line to make compiler happy, since it thinks list might be empty return "whatever"; } // which remaining candidate is least favorite? public String bottom() { // find and store the last name, overwriting all others String last = "whatever"; for (String name : list) last = name; // only the last one remains return last; } // remove candidate from the ballot public void cut(String candidate) { Queue<String> newList = new Queue<String>(); // keep everyone, in order, except the one we want to eliminate for (String name : list) { if (!name.equals(candidate)) newList.enqueue(name); } // did we actually eliminate someone? if (newList.size() == list.size()) throw new RuntimeException(candidate + " not on list"); // save the changes list = newList; } public static void main(String[] args) { String[] testPrefs = {"Doug", "Nanxi", "Bebe", "Aleksey"}; Ballot b = new Ballot(testPrefs); System.out.println(b); // toString(): "Doug > Nanxi > Bebe > Aleksey" System.out.println(b.top()); // gives "Doug" System.out.println(b.bottom()); // gives "Aleksey" b.cut("Doug"); System.out.println(b); // gives "Nanxi > Bebe > Aleksey" System.out.println(b.top()); // "Nanxi" - change from original top() b.cut("Bebe"); System.out.println(b); // gives "Nanxi > Aleksey" b.cut("Bebe"); // throws a RuntimeException } }