top of page

Coding Practice: Election Example

  • Writer: Ruby Moley
    Ruby Moley
  • Sep 28, 2024
  • 5 min read

Updated: Dec 3, 2024

Published on 09 / 28 / 2024


Hello! This week, I tackled a large coding practice assignment. I wanted to attempt to make a code that mimics an Election, with voters, voting registration, and polling stations. I understand this looks very complex to the eye, but you can read signatures and variable names to comprehend the code. Additionally, each class has comments (that either start with // or /**) that explain each section of the code.


Coding, while logical and mathematical in nature, is very creative. It takes a lot of time and patience to create something like this (this example alone took roughly 6-7 hours). This creative outlet accesses and unlocks parts of your brain you wouldn't normally use. I think of coding as solving a Rubix Cube or creating a really complex machine. It is so satisfying to see it succeed!


Now, let's get into the code! If you want to run this code for yourself, you will have to use an external program.


Voter Class

/**
 * This class represents a voter object.
 */

/**
 * @author rubym
 */
public class Voter {
	private String name, voterID;

	// Getters
	public String getName() {
		return name;
	}
	public String getVoterID() {
		return voterID;
	}
	
	// Constructor
	public Voter(String name, String voterID) {
		super();
		this.name = name;
		this.voterID = voterID;
	}
	
	/**
	 * This method overrides the 'equals' method defined in Object.
	 */
	@Override
	public boolean equals (Object obj) {
		if (obj == null) return false;
		Voter voter = (Voter) obj;
		return this.name.equalsIgnoreCase(voter.getName()) &&
			   this.voterID.equalsIgnoreCase(voter.getVoterID());
	}
}

Registration Class

/**
 * This class represents a list of registered voters.
 */

import java.util.ArrayList;
import java.io.PrintWriter;

/**
 * @author rmoley
 */
public class Registration {
	public ArrayList<Voter> voters;
	private PrintWriter output;
	
	// getter
	public ArrayList<Voter> getVoters(){ 
		return voters; 
	}
	
	// constructor
	public Registration (PrintWriter output) {
		voters = new ArrayList<>();
		this.output = output;
	}
	
	/**
	 * This method will add a new voter to the 
	 * registration list.
	 * @param voter The new voter to be added.
	 */
	public void addVoter(Voter voter) throws AlreadyRegisteredException {
		for (Voter v : voters) {
			if (v.getVoterID().equalsIgnoreCase(voter.getVoterID())) {
				throw new AlreadyRegisteredException("The attempted voter ID of " + voter.getName() + " " + 
						 							voter.getVoterID() + " is already registered.");
			} 
		}
		voters.add(voter);
	}
	
	/**
	 * This method prints out the list of registered voters.
	 */
	public void printVoters() {
		for (Voter voter : voters) {
			output.println(voter.getName() + " " + voter.getVoterID());
		}
	}
}

Polling Station Class

/**
 * This class represents a list of voters at a polling station.
 * Allows user to add voters to line and print the list.
 */

import java.util.LinkedList;
import java.io.*;

/**
 * @author rubym
 */

public class PollingStation {
	private LinkedList<Voter> voterLine;
	private PrintWriter output;
	public Registration registeredVoters;

	// getter
	public LinkedList<Voter> getVoterLine() {
		return voterLine;
	}

	// constructor
	public PollingStation(PrintWriter output, Registration registeredVoters) {
		this.voterLine = new LinkedList<>();
		this.output = output;
		this.registeredVoters = registeredVoters;
	}
	
	/**
	 * This method will add a new voter to the line at the
	 * polling station.
	 * @param voter The new voter to be added to the line.
	 * @throws OutOfCountyException, AlreadyVotedException
	 */
	public void addVoter(Voter voter, int stationSelection) throws AlreadyVotedException, OutOfCountyException {
		// check if voter has voted at the polling station
		if (!voterLine.contains(voter)) {
			switch (stationSelection) {
			case 1:
				if(voter.getVoterID().substring(0,2).equalsIgnoreCase("JC")) {
					voterLine.add(voter);
				} else { 
					throw new OutOfCountyException("This person must live in Johnson County to vote here: " + 
						 							voter.getName() + " " + voter.getVoterID() + " ");
				}
				break;
			case 2:
				if(voter.getVoterID().substring(0,2).equalsIgnoreCase("LA")) {
					voterLine.add(voter);
				} else { 
					throw new OutOfCountyException("This person must live in Los Angeles County to vote here: " + 
												 	voter.getName() + " " + voter.getVoterID() + " ");
				}
				break;
			case 3:
				if(voter.getVoterID().substring(0,2).equalsIgnoreCase("WA")) {
					voterLine.add(voter);
				} else { 
					throw new OutOfCountyException("This person must live in Washington County to vote here: " + 
						 							voter.getName() + " " + voter.getVoterID() + " ");
				}
				break;
			default: throw new IllegalArgumentException("Invalid station selection, try again.");
			}
		} else {
			throw new AlreadyVotedException("This person already voted: " + 
											voter.getName() + " " + 
											voter.getVoterID());
		}
	}

	/**
	 * This method prints all the voters at a given polling station.
	 */
	public void printVoters() {
		for (Voter voter : voterLine) {
			output.println(voter.getName() + " " + voter.getVoterID());
		}
	}
}

Election Class (Test Class)

/**
 * This class represents the voting process in an election. It 
 * will simulate voters registering, heading to polling stations, 
 * and voting. Voters will be read from text files and voting outputs will
 * go to a report file.
 */

import java.io.*;
import java.util.Scanner;

/**
 * @author rubym
 */
public class Election {
	public static void main(String[] args) {
		BufferedReader buffer = null;
		PrintWriter writer = null;
		Scanner scan = null;
		String line = "";
		Registration registeredVoters;
		PollingStation pollingApple, pollingButter, pollingCat;
		
		try {
			writer = new PrintWriter(new FileWriter("report.txt"));
			registeredVoters = new Registration(writer);
			pollingApple = new PollingStation(writer, registeredVoters);
			pollingButter = new PollingStation(writer, registeredVoters);
			pollingCat = new PollingStation(writer, registeredVoters);
			
			// populate ArrayList in Registration with potential voters
			buffer = new BufferedReader(new FileReader("potentialVoters.txt"));
			while ((line = buffer.readLine()) != null) {
				scan = new Scanner (line);
				try {
					registeredVoters.addVoter(new Voter (scan.next(), scan.next()));
				} catch (AlreadyRegisteredException e) {
					writer.println(e.toString());
				} finally {
					scan.close();
				}
			}
			buffer.close();
			
			// process registered voters to selected voting stations
			buffer = new BufferedReader(new FileReader("votingList.txt"));
			while ((line = buffer.readLine()) != null) {
				scan = new Scanner (line);
				Voter voter = new Voter (scan.next(), scan.next());
				int stationSelection = scan.nextInt();
				try {
					// check that voter is registered
					if(registeredVoters.getVoters().contains(voter)) {
						// check if voter is already registered
						if (!pollingApple.getVoterLine().contains(voter) || 
							!pollingButter.getVoterLine().contains(voter) ||
							!pollingCat.getVoterLine().contains(voter)) {
							// process vote to desired station
							switch (stationSelection) {
							case 1:
								pollingApple.addVoter(voter, stationSelection);
							break;
							case 2:
								pollingButter.addVoter(voter, stationSelection);
								break;
							case 3:
								pollingCat.addVoter(voter, stationSelection);
								break;
							default:
								writer.println("Invalid station number for " + voter.getName() + " " + 
												voter.getVoterID() + ". Pick Stations 1, 2, or 3.");
							} 
						}
					} else {
						throw new NotRegisteredException("Voter is not registered: " + 
														 voter.getName() + " " + voter.getVoterID());
					}
				} catch (AlreadyVotedException | OutOfCountyException | NotRegisteredException e) {
					writer.println(e.toString());
				} finally {
					scan.close();
				}
			}
			buffer.close();
			
			// Print registration list and polling stations
			writer.println(" - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ -  - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ - ");
			writer.println("Registered Voters List: ");
			registeredVoters.printVoters();
			
			writer.println(" - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ -  - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ - ");
			writer.println("Johnson County Polling Station List: ");
			pollingApple.printVoters();
			
			writer.println(" - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ -  - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ - ");
			writer.println("Los Angeles County Polling Station List: ");
			pollingButter.printVoters();
			
			writer.println(" - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ -  - ⊹ ࣪ ˖ - - ⊹ ࣪ ˖ - ");
			writer.println("Washington County Polling Station List: ");
			pollingCat.printVoters();
			
			writer.close();
		} catch (FileNotFoundException e) {
			System.out.println(e.toString());
		} catch (IOException e) {
			System.out.println(e.toString());
		}
	}
}

Thank you for tuning in to today's post! Let me know if you liked the code post and if I should post more code.

 
 
 

Comments


file (18).png

Let's chat!!!

Thanks for submitting!

© 2035 by Annabelle. Wix

file (19).png
bottom of page