Question

VotePersonalldentification voterLastName:String voterFirstName:String -voterSIN: Integer voterAddress:String -voterProvince:S

Utilizing the class diagram above, implement the voting system using JAVA. You will need a main method to allow a voter to register and vote (you need to take in user input). You need to assume getters, setters, constructors, and toString methods; and you need to take in the user input and validate it as well. Comment the code well and submit screenshot testing within your PDF. Hint: you can research regular expressions for the validation functions.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

voting system in java

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

abstract public class Election {
boolean done = false; // when true, break out of processing loop

class Candidate {
   String name;
   String party;
   int voteCount;
   Candidate(String name, String party) {
       this.name = name;
       this.party = party;
       voteCount = 0;
   }
}
class Voter {
   String name;
   String party;
   boolean voted;
   Voter(String name, String party) {
       this.name = name;
       this.party = party;
       voted = false;
   }
}

protected Hashtable candidates = new Hashtable();
protected Hashtable voters = new Hashtable();
StringBuffer OfficialRecord = new StringBuffer();

void log(String s) {  
OfficialRecord.append(s + '\n');
System.out.println(s);
}
  
public static void main(String[] args) {
// Instantiate an election
Election e = null;
if (args.length > 0) {
if (args[0].compareTo("General") == 0) {
   e = new GeneralElection();
   } else if (args[0].compareTo("Primary") == 0) {
   e = new PrimaryElection();
   }
   }
if (e == null) {
System.out.println("Specify General or Primary");
   return;
}
// Open input file
FileReader in;
String filename = "election.dat";
try {
in = new FileReader(filename);
} catch (IOException ex) {
   e.log("Cannot open " + filename);
   return;
}
// Processing
try {
   e.process(in);
in.close();
} catch (IOException ex) {
   e.log("Something Bad Happened");
}
} // main


void process(FileReader rdr) throws IOException {
BufferedReader b = new BufferedReader(rdr);
String msg;
MessageFactory MF = new MessageFactory();
while (!done && b.ready()) {
   msg = b.readLine();
   // In a real system, we would probably use multithreading
   // and place each message in a queue.
   Message m = MF.create(msg);
   if (m != null) {
   try {
   m.perform(this);
   } catch (ElectionException ex) {
   log(ex.getLogMessage());
   }
   }
}
}

void vote(String cand, String voter) throws ElectionException {
verify(cand, voter);
Candidate c = getCandidate(cand);
c.voteCount += 1;
Voter v = getVoter(voter);
v.voted = true;
log(voter + " voted for " + cand);
}

/** Register a voter **/
void register(String voter, String party) {
Voter v = (Voter) voters.get(voter);
if (v != null) {
v.party = party;
   log(voter + " affiliation changed to " + party);
} else {
voters.put(voter, new Voter(voter, party));
log("Register voter " + voter+ " as a " + party);
}
}

/** Register a candidate **/
void candidate(String cand, String party) {
Candidate c = (Candidate) candidates.get(cand);
if (c != null) {
c.party = party;
log(cand + " affiliation changed to " + party);
return;
} else {
candidates.put(cand, new Candidate(cand, party));
log("Register candidate " + cand + " as a " + party);
}
}

/** List all of the candidates, PrimaryElection overrides **/
void list(String voter) throws ElectionException {
   Enumeration it = candidates.elements();
   log("Candidate list for " + voter);
   int counter = 0;
   while(it.hasMoreElements()) {
   Candidate c = (Candidate) it.nextElement();
   log(" " + ++counter + c.name);
   }
}

/** Report the vote count for each candidate **/
void tally() throws ElectionException {
   log("Tally");
   Enumeration it = candidates.elements();
   while(it.hasMoreElements()) {
       Candidate c = (Candidate) it.nextElement();
       log(" " + c.name + " (" + c.party + ") " + c.voteCount);
   }
}

/** Reset all of the vote counts to 0 and voters as not voted **/
void reset() {
   log("Reset");

   Enumeration ic = candidates.elements();
   while(ic.hasMoreElements()) {
       Candidate c = (Candidate) ic.nextElement();
       c.voteCount = 0;
   }
     
   Enumeration iv = voters.elements();
   while(iv.hasMoreElements()) {
       Voter v = (Voter) iv.nextElement();
       v.voted = false;
   }
     
}

void dump() {
   System.out.println("\n\n----------------Start of Dump-------------------");
   System.out.println(OfficialRecord);
   System.out.println("---------------End of Dump------------------------");
}

void exit(){
   done = true;
   log("Exit");
}

/** Retrieve a voter object
**/
Voter getVoter(String voter) throws NotRegisteredException {
Voter v = (Voter) voters.get(voter);
if (v == null) {
   throw new NotRegisteredException(voter);
}
return v;
}

/** Retrieve a candidate object
**/
Candidate getCandidate(String name) throws NotACandidateException {
Candidate c = (Candidate) candidates.get(name);
if (c == null) {
   throw new NotACandidateException(name);
}
return c;
}

/** Return true if candidate and voter parties match
**/
boolean sameParty(Candidate c, Voter v) {
return (c.party.compareTo(v.party) == 0);
}
      
}; // Election

/*****************************************************************************
MESSAGE CLASSES
*****************************************************************************/

abstract class Message {
String type;

abstract void perform(Election e) throws ElectionException;

void parse(String msg, String[] args) {
StringBuffer b = new StringBuffer();
type = msg.substring(0,4);
int count = 0;
int start = msg.indexOf('<');
int end = msg.indexOf('>');
while (count < args.length && start < end && start >= 0) {
   args[count++] = msg.substring(start + 1, end);
start = msg.indexOf('<', end);
end = msg.indexOf('>', start);
}
} // Parse
};// Message

/** Request to record a vote **/
class VoteMessage extends Message {
String[] args = new String[2]; // Expects two arguments, candidate and voter.
VoteMessage(String s) {
parse(s, args);
}
// Record the vote
void perform(Election e) throws ElectionException {
e.vote(args[0], args[1]);
}
};

/** Request to register a new voter **/
class RegisterMessage extends Message {
String[] args = new String[2]; // Expects two arguments, voter and party
RegisterMessage(String s) {
parse(s, args);
}
// Register the voter
void perform(Election e) throws ElectionException {
e.register(args[0], args[1]);
}
}; //RegisterMessage

/** Request to register a candidate **/
class CandidateMessage extends Message {
String[] args = new String[2];
CandidateMessage(String s) {
parse(s, args);
}
// Register the candidate
void perform(Election e) throws ElectionException {
e.candidate(args[0], args[1]);
}
}; // End CandidateMessage

/** Request to list the candidates available to a particular voter **/
class ListMessage extends Message {
String[] args = new String[1]; // Expects one argument, a voter
ListMessage(String s) {
parse(s, args);
}
// Display the list
void perform(Election e) throws ElectionException {
e.list(args[0]);
}
};

/** Request that the program - and the election - terminate
**/
class ExitMessage extends Message {
void perform(Election e) throws ElectionException {
e.exit();
}
};

/** Request a listing of all of the transactions for the election
**/
class DumpMessage extends Message {
void perform(Election e) throws ElectionException {
e.dump();
}
};

/** Request that the election be restarted
**/
class ResetMessage extends Message {
void perform(Election e) throws ElectionException {
e.reset();
}
};

/** Request a tally of all of the candidates and the number of
** votes they have received
**/
class TallyMessage extends Message {
void perform(Election e) throws ElectionException {
e.tally();
}
};


class MessageFactory {

public static Message create(String msg) {
Message result = null;
char type = msg.charAt(0);
// Note, if this were real code we would check the complete message id.
switch (type) {
   case 'D': // dump
   result = new DumpMessage();
       break;
   case 'E': // Exit
       result = new ExitMessage();
       break;
case 'V': // VOTE
       result = new VoteMessage(msg);
       break;
   case 'R': // RGST or REST
   if (msg.charAt(1) == 'G') {
       result = new RegisterMessage(msg);
   } else {
       result = new ResetMessage();
       }
       break;
   case 'C': // CAND
       result = new CandidateMessage(msg);
       break;
   case 'L': // LIST
       result = new ListMessage(msg);
       break;
   case 'T': // TLLY
       result = new TallyMessage();
       break;
} // switch
return result;
} // create
}; // MessageFactory

/** GeneralElection
** Voters can vote for any candidate
**/
class GeneralElection extends Election {
GeneralElection() {
log("General Election");
}

void verify(String candidate, String voter)throws ElectionException {
Voter v = getVoter(voter);
if (v.voted) { // check that voter hasn't already voted
throw new AlreadyVotedException(voter);
}
}
};

/** PrimaryElection
** Voters can only vote for candidates in the same party
**/
class PrimaryElection extends Election {
PrimaryElection() {
log("Primary Election");
}

void verify(String candidate, String voter) throws ElectionException {
// check that voter hasn't already voted
Voter v = getVoter(voter);
if (v.voted) {
throw new AlreadyVotedException(voter);
}
// check that party affiliations are the same
Candidate c = getCandidate(candidate);
if (!sameParty(c, v)) {
throw new WrongPartyException(voter, c.party);
}
}

/** List only the candidates for the voters own party **/
void list(String voter) throws ElectionException {
Enumeration it = candidates.elements();
Voter v = getVoter(voter);
log("List for " + voter);
int counter = 0;
while(it.hasMoreElements()) {
   Candidate c = (Candidate) it.nextElement();
   if (sameParty(c, v)) {
   log(" " + ++counter + c.name);
   }
}
}
};

abstract class ElectionException extends Exception {
abstract String getLogMessage();
};


class AlreadyVotedException extends ElectionException {
String voter;
AlreadyVotedException(String voter) {this.voter = voter;}
String getLogMessage() {return voter + " already voted";}
};

class WrongPartyException extends ElectionException {
String voter;
String party;
WrongPartyException(String voter, String party) {
this.voter = voter;
this.party = party;
}
String getLogMessage() {return voter + " cannot vote for a " + party;}
};

class NotRegisteredException extends ElectionException {
String name;
NotRegisteredException(String name) {this.name = name;}
String getLogMessage() {return name + " is not registered";}
};

class NotACandidateException extends ElectionException {
String name;
NotACandidateException(String name) {this.name = name;}
String getLogMessage() {return name + " is not a candidate";}
};

Add a comment
Know the answer?
Add Answer to:
Utilizing the class diagram above, implement the voting system using JAVA. You will need a main...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Utilizing the class diagram above, implement the voting system. You will need a main method to...

    Utilizing the class diagram above, implement the voting system. You will need a main method to allow a voter to register and vote (you need to take in user input). You need to assume getters, setters, constructors, and toString methods; and you need to take in the user input and validate it as well. Comment the code well and submit screenshot testing within your PDF. Hint: you can research regular expressions for the validation functions. Just need help with the...

  • Write a program that supports the three phases (setup, voting and result-tallying) which sets up and...

    Write a program that supports the three phases (setup, voting and result-tallying) which sets up and executes a voting procedure as described above. In more details: You can start with the given skeleton (lab6_skeleton.cpp). There are two structures: Participant structure, which has the following members: id -- an integer variable storing a unique id of the participant (either a candidate or a voter). name -- a Cstring for storing the name of the participant.. hasVoted -- a boolean variable for...

  • (2 bookmarks) In JAVA You have been asked to write a program that can manage candidates...

    (2 bookmarks) In JAVA You have been asked to write a program that can manage candidates for an upcoming election. This program needs to allow the user to enter candidates and then record votes as they come in and then calculate results and determine the winner. This program will have three classes: Candidate, Results and ElectionApp Candidate Class: This class records the information for each candidate that is running for office. Instance variables: first name last name office they are...

  • I need the following written in Java please, thank you ' We want you to implement...

    I need the following written in Java please, thank you ' We want you to implement a java class that will show details on users and throw exceptions where needed. The following requirements specify what fields you are expected to implement in your User class: - A private String firstName that specifies the first name of the user - A private String lastName that specifies the last name of the user - A private int age that specifies user's age...

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • no buffered reader. no try catch statements. java code please. And using this super class: Medialtemjava...

    no buffered reader. no try catch statements. java code please. And using this super class: Medialtemjava a Create the "middle" of the diagram, the DVD and ForeignDVD classes as below: The DVD class will have the following attributes and behaviors: Attributes (in addition to those inherited from Medialtem): • director:String • rating: String • runtime: int (this will represent the number of minutes) Behaviors (methods) • constructors (at least 3): the default, the "overloaded" as we know it, passing in...

  • Using loops with the String and Character classes. You can also use the StringBuilder class to...

    Using loops with the String and Character classes. You can also use the StringBuilder class to concatenate all the error messages. Floating point literals can be expressed as digits with one decimal point or using scientific notation. 1 The only valid characters are digits (0 through 9) At most one decimal point. At most one occurrence of the letter 'E' At most two positive or negative signs. examples of valid expressions: 3.14159 -2.54 2.453E3 I 66.3E-5 Write a class definition...

  • You need to program a simple book library system. There are three java classes Book.java   //...

    You need to program a simple book library system. There are three java classes Book.java   // book object class Library.java   //library class A2.java //for testing The Book.java class represents book objects which contain the following fields title: a string which represents the book title. author: a string to hold the book author name year: book publication year isbn: a string of 10 numeric numbers. The book class will have also 3 constructors. -The default no argument constructor - A constructor...

  • Hello Guys. I need help with this its in java In this project you will implement...

    Hello Guys. I need help with this its in java In this project you will implement a Java program that will print several shapes and patterns according to uses input. This program will allow the use to select the type (say, rectangle, triangle, or diamond), the size and the fill character for a shape. All operations will be performed based on the user input which will respond to a dynamic menu that will be presented. Specifically, the menu will guide...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT