Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Assignments

CSCI125Code


Votes.java

import java.util.*;

/**
 * A simple vote keepin class. It keeps track of the number of times each person is voted for.
 *
 * @author Charles Cusack
 * @version 10/25/2024
 */
public class Votes
{
    private HashMap<String,Integer> votes; // The map of name to number of votes
   
    /**
     * Construct a new Votes with no votes for anybody.
     */
    public Votes() {
        votes = new HashMap<>();
    }
   
    /**
     * Add one vote for name.
     * @param name the person to add a vote for.
     */
    public void vote(String name) {
        Integer numVotes = votes.get(name);
        if(numVotes==null) {
            votes.put(name,1);
        } else {
            votes.put(name,numVotes+1);
        }
    }
   
    /**
     * Returns the number of votes for name.
     *
     * @return the number of votes that name currently has,
     * or 0 if name does not currently have any votes.
     */
    public int howManyVotes(String name) {
        return votes.getOrDefault(name, 0);
        // The longer way to do it (likely what the
        // getOrDefault method is doing).
        // Integer numVotes = votes.get(name);
        // if(numVotes==null) {
            // return 0;
        // } else {
            // return numVotes;
        // }
    }
   
    private int tallyVotes() {
        int totalVotes = 0;
        for(Map.Entry<String,Integer> vote : votes.entrySet()) {
            totalVotes+=vote.getValue();
        }
        return totalVotes;
    }
   
    public String voteSummary() {
        StringBuffer sb = new StringBuffer();
        sb.append("There was a total of "+tallyVotes()+" votes as follows:\n");
        for(Map.Entry<String,Integer> vote : votes.entrySet()) {
            sb.append(vote.getKey());
            sb.append(":");
            sb.append(vote.getValue());
            sb.append("\n");
        }
        return sb.toString();
    }
}