package election; import java.util.StringTokenizer; /* A voter's ranked list of candidates. This is simply a queue of * strings, with the top-ranked candidate at the front. The ballot * also has a weight (how many votes does it count for?). We provide * a nice constructor that obtains a ballot from a string. */ public class Ballot extends sequence.ArrayQueue { protected float weight = 1; /** Constructs a Ballot holding the names in this string. * The names are assumed to be comma-separated. * For example, "Eckert, Mauchly, von Neumann" would return * a ballot with 3 names, with Eckert on top. */ public Ballot(String s) { super(ballotLength(s)); // make queue just long enough for this ballot StringTokenizer st = tokenizer(s); while (st.hasMoreTokens()) enqueue(st.nextToken().trim()); } /** Returns the top name on this ballot. */ public String topName() { return (String) front(); } /** Returns the current weight of this ballot. */ public float weight() { return weight; } /** Multiplies the weight of this ballot by f. * Use this method to reduce the value of a ballot that has been partly used up. */ public void multWeight(float f) { this.weight *= f; } // ------- PROTECTED CONVENIENCE METHODS ------- protected static StringTokenizer tokenizer(String s) { return new StringTokenizer(s, ","); } protected static int ballotLength(String s) { StringTokenizer st = tokenizer(s); int i; for (i=0; st.hasMoreTokens(); i++) st.nextToken(); return i; } }