Question

Using JAVA You have been asked to write a program that can manage candidates for an...

Using 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 running for
  • the party they represent
  • total votes
  • a boolean value to record if they won

Methods:

  • Custom constructor that accepts first and last name, office and party
  • Custom constructor that accepts an instance of another customer
  • Getters for all instance variables and setters for total votes and the boolean variable
  • toString: This method should output the details of a Candidate. See sample run
  • equals: This method should determine if a Candidate passed in is equal to the current candidate. Two candidates are equal if their first and last name are the same and their parties are equal.

Results Class: This class stores all of the candidates in an array using aggregation.

     Constants:

  • BLOCK_SIZE set to 3. This variable represents the size of an array and the size it increases by each time it is resized.

Instance variables:

  • An array that stores Candidates
  • An integer that stores the actual number of elements that are populated in the candidate array
  • An array that stores Strings that represent each of the offices represented
  • An integer value that stores the actual number of elements that are populated in the offices array

Methods:

  • Constructor: Set a default constructor that does the following:
    • Instantiates the two arrays to BLOCK_SIZE.
    • Sets the two size variables to 0.
  • Getters for the two sizes
  • toString: This method should call the Candidate toString for each item in the array
  • hasCandidate: This method accepts a Candidate and using a for loop, searches the candidate array for the received candidate. If the candidate is found, return true. Otherwise, return false.
  • isCandidatesFull: This method returns true if the size of the array matches the length of the array. Otherwise, it returns false.
  • isOfficeFull: This method returns true if the size of the array matches the length of the array. Otherwise, it returns false.
  • addCandidate(): This method will prompt and accept user input to get the information needed to create a candidate.
    • It will use the hasCandidate method to ensure that a candidate is not on the list before being added to the list. If candidate is already on the list, return a message that reads, “Candidate already on ballot.”
    • If candidate is not on the list, then call the overloaded addCandidate method and pass in the candidate to be added.
  • addCandidate(Candidate c): This private method accepts the candidate that will be added to the array.
    • First you must verify that the list is not full. If it is full, then you call the resizeCandidate method.
    • Create a new instance of candidate and add it to the candidates array.
    • Determine whether this is a new office by searching the office array for a match. If no match (or array is empty), add the office to the office array, but you must first determine if the array is full, and if so, resize it.
  • resizeCandidate(): This method creates a temporary array that is Candidate array length plus BLOCK_SIZE as the length of the temporary array and then setting the temporary array to the original array.
  • resizeOffice(): This method creates a temporary array that is Office array length plus BLOCK_SIZE as the length of the temporary array and then setting the temporary array to the original array.
  • addVotes: This method will prompt the user to enter votes for each candidate.
  • determineWinner: This method will display a list of offices that currently have candidates and the user will choose which office they want to determine winner for. It will build a menu of offices, from the offices array and display it to the user. It will call the method createCandidateListByOffice and will pass the users input to the method.
  • createCandidateListByOffice: This private method accepts user input and will build a temporary array that contains a list of all candidates that are running for the specific office the user has selected.
  • findHighestVotes: This private method receives the temporary array and the size of the array from createCandidateListByOffice method.
    • If there is only one candidate running for that office, then the candidate must have at least one vote to win.
    • If there is more than one candidate, then it will search the temp array for the most votes for that office. Set the boolean won value for the winning candidate to true.
    • If the scores are equal, then there is no winner.
  • displayWinners: This method outputs all candidates who have won their race.

ElectionApp:This is your main program. This class will display the menu and drive all the activities.

     Methods:

  • Main Method: This method will instantiate any variables, call the output menu and then call methods in the results class based on the choices of the user. The program should continue until the user selects option 6. It should validate the user input to ensure that the numbers range from 1 to 6 and will repeat the menu if the option is not valid.
  • outputMenu: This method displays the menu

Choose from the following options:

1- Add a candidate

2- Add votes

3- Determine winner

4- Display a list of candidates

5- Display winners

6- Exit

Design Requirements

  • Create a class diagram for 2 classes – Candidate and Results
0 0
Add a comment Improve this question Transcribed image text
Answer #1

====================================Candidate.java==========================================


public class Candidate {
   String firstName;
   String lastName;
   String office;
   String party;
   int totalVotes=0;
   boolean winOrLose;
  
   public Candidate(String fName,String lName,String office,String party){
       this.firstName=fName;
       this.lastName=lName;
       this.office=office;
       this.party=party;
   }
  
   public Candidate(Candidate customer){
       this.firstName=customer.firstName;
       this.lastName=customer.lastName;
       this.office=customer.office;
       this.party=customer.party;
   }
  
   //setters
   public void setTotalVotes(int totalVotes) {
       this.totalVotes = totalVotes;
   }

   public void setWinOrLose(boolean winOrLose) {
       this.winOrLose = winOrLose;
   }
  
   //getters for all instance variable
   public String getFirstName() {
       return firstName;
   }

   public String getLastName() {
       return lastName;
   }

   public String getOffice() {
       return office;
   }

   public String getParty() {
       return party;
   }

   public int getTotalVotes() {
       return totalVotes;
   }

   public boolean isWinOrLose() {
       return winOrLose;
   }
  
   public String toString()
{
return "First Name: "+firstName + ",Last Name: " + lastName + ",Party: " + party + ",Office:" + office;
}
  
   //custom toString method to display winner and votes.......(NOT IN THE REQUIREMENTS)
   public String toString_winner(){
       return firstName+" "+lastName+" party:"+party+",Office: "+office+",number_of_votes: "+ totalVotes;
   }
  
   public boolean equals(Candidate c) {
   return (this.firstName==c.firstName &&this.lastName==c.lastName&& this.party==c.party);
   }  
}

========================================Results.java===========================================

import java.security.AlgorithmConstraints;
import java.util.ArrayList;
import java.util.Scanner;


public class Results {
   int BLOCK_SIZE=3;
//   ArrayList<Candidate> c;
   Candidate[] cand;
   int arrayLength;
//   ArrayList<String> Office;
   String[] office;
   int numOffice;

   public Results(){
       cand= new Candidate[BLOCK_SIZE];
       office=new String[BLOCK_SIZE];
       arrayLength=numOffice=0;
      
   }
  
   public int getArrayLength() {
       return arrayLength;
   }

   public int getNumOffice() {
       return numOffice;
   }
  
   public String toString(){
       String str="";
       for(int i=0;i<cand.length;i++){
           str=str+cand[i].toString()+"\n";
       }
       return str;
   }
  
   public boolean hasCandidate(Candidate c){
       for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){
           if(cand[i].equals(c))return true;
       }
       }
       return false;
   }
  
   public boolean isCandidatesFull(){
       return cand.length==arrayLength;
   }
  
   public boolean isOfficeFull(){
       return office.length==numOffice;
   }
  
   public void addCandidate(){
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter first name");
       String fn= sc.nextLine();
       System.out.println("Enter last name");
       String ln= sc.nextLine();
       System.out.println("Enter office");
       String o= sc.nextLine();
       System.out.println("Enter party");
       String p= sc.nextLine();
       Candidate candidate=new Candidate(fn,ln,o,p);
       if(hasCandidate(candidate)){
           System.out.println("Candidate already on ballot");
       }else{
           addCandidate(candidate);
           //............
           arrayLength++;  
       }
   }
   //overloaded
   private void addCandidate(Candidate c){
       boolean full=isCandidatesFull();
       if(full){resizeCandidate();}
       for(int i=0;i<cand.length;i++){
           if(cand[i]==null){
               cand[i]=c;
               break;
           }
       }
      
       //.............
       boolean check=false;
       for(int i=0;i<office.length;i++){
           if(office[i]!=null){
           if(office[i].equals(c.getOffice())){
               check=true;
               break;
           }
           }
       }
      
       if(!check){
           numOffice++;
       if(isOfficeFull()){resizeOffice();}
      
       for(int i=0;i<office.length;i++){
           if(office[i]==null){
               office[i]=c.office;
               break;
           }
       }
   }
}
  
   public void resizeCandidate(){
       Candidate[] temp= new Candidate[arrayLength+BLOCK_SIZE];
       for(int i=0;i<cand.length;i++){
           temp[i]=cand[i];
       }
       cand=temp;
   }
  
   public void resizeOffice(){
       String[] temp= new String[numOffice+BLOCK_SIZE];
       for(int i=0;i<office.length;i++){
           temp[i]=office[i];
       }
       office=temp;
   }
  
   //only one vote can be given to the candidate
   public void addVotes(){
       boolean vote;
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter votes for each candidae");
       for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){
           System.out.println("do you want to vote for "+cand[i].toString()+" (true OR false)");
       vote=sc.nextBoolean();
       if(vote){
           cand[i].totalVotes=cand[i].totalVotes+1;
       }
       }
   }
      
       //................
       //setting winOrLose=false of every candidate to false every time you add votes
               for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){
               cand[i].winOrLose=false;
       }
           }
              
}

   //...................
   //(NOT IN THE REQUIREMENTS)
   // custom method to add votes to vote for candidate in numbers (ie more than one vote can be given to a candidate)
   public void addVotes2(){
       int vote;
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter votes for each candidae");
       for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){
           //System.out.println("do you want to vote for"+cand[i].toString()+" (true OR false)");
           System.out.println("enter number! of votes to vote for "+cand[i].toString());
          
       vote=sc.nextInt();
       if(vote>0){
           cand[i].totalVotes=cand[i].totalVotes+vote;
       }
       }
   }
      
       //setting winOrLose=false of every candidate to false every time you add votes
       for(int i=0;i<cand.length;i++){
   if(cand[i]!=null){
       cand[i].winOrLose=false;
}
   }
      
}
  
   public void determineWinner(){
       System.out.println("===OFFICE MENU===");
       for(int i=0;i<office.length;i++){
           if(office[i]!=null)System.out.println(office[i]+"\n");
       }
       System.out.println("===MENU Ends===\n");
      
       System.out.println("Pleas enter office you want to detemine winner ! \n");
       Scanner sc=new Scanner(System.in);
       String s=sc.nextLine();
      
       Candidate[] list=createCandidateListByOffice(s);
       findHighestVotes(list,list.length);
   }
  
   private Candidate[] createCandidateListByOffice(String off){
       Candidate[] temp=null;
       ArrayList<Candidate> temp2=new ArrayList<Candidate>() ;
       System.out.println("candidate running for office-"+off+ "are:");
for(int i=0;i<cand.length;i++){
   if(cand[i]!=null){
   if(cand[i].getOffice().equals(off)){
   System.out.println(cand[i].getFirstName()+" "+cand[i].getLastName());
   temp2.add(cand[i]);
   }
}
}
System.out.println();
//for casting Object[] to Candidate[]
Candidate[] arr= new Candidate[temp2.size()];
temp= temp2.toArray(arr);
  
return temp;
   }
  
   private void findHighestVotes(Candidate[] c,int size){
  
       if(size==1){
   if(c[0].getTotalVotes()>=1){
   c[0].winOrLose=true;
   // set win or lose in orignal candidate array
   for(int i=0;i<cand.length;i++){
       if(cand[i]!=null){
       if(cand[i].equals(c[0])){
           cand[i].winOrLose=true;
       }
   }
   }
}
}
  
if(size>1){
   int tempcount=0;
   int tempWinnerIndex=0;
  
   //...............
  
   // getting index of the highest voted candidate
   for(int i=0;i<c.length;i++){
       if(c[i].getTotalVotes()>tempcount){
           tempcount=c[i].getTotalVotes();
           tempWinnerIndex=i;
       }
   }
  
   // checking if any other candiadates have same number of votes
   int tempi=0;
   for(int i=0;i<c.length;i++){
       if(c[i].getTotalVotes()==c[tempWinnerIndex].getTotalVotes()){
           tempi++;
       }
   }
  
   if(tempi>1){
       System.out.println("Following candidte has same number of votes no one wins");
       for(int i=0;i<c.length;i++){
       if(c[i].getTotalVotes()==c[tempWinnerIndex].getTotalVotes()){
           System.out.println(c[i].toString());
       }
   }
       System.out.println();
   }else{
      
       // set win or lose in orignal candidate array
   for(int i=0;i<cand.length;i++){
       if(cand[i]!=null){
       if(cand[i].equals(c[tempWinnerIndex])){
           cand[i].winOrLose=true;
       }
   }
}
  
   }
}
}
  
   public void displayWinners(){
       //determineWinner();
       System.out.println("candidate who won are");
       for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){  
           if(cand[i].winOrLose==true){
               System.out.println(cand[i].toString_winner());
           }
       }
   }
}
  
   public void displayListOfCandidates(){
       for(int i=0;i<cand.length;i++){
           if(cand[i]!=null){  
           System.out.println(cand[i].toString());
           }
       }
   }
}

=================================== ElectionApp.java==========================

import java.util.Scanner;


public class ElectionApp {

   public static void main(String[] args) {
       Results r=new Results();
       // TODO Auto-generated method stub
  
       while(true){
       System.out.println("Choose from the following options: \n"+
       "1- Add a candidate \n"+
       "2- Add votes \n"+
       "3- Determine winner \n"+
       "4- Display a list of candidates \n"+
       "5- Display winners \n"+
       "6- Exit\n");
      
       Scanner sc=new Scanner(System.in);
       int choice = sc.nextInt();
       switch(choice){
       case 1:
           r.addCandidate();break;
       case 2:
           //r.addVotes();
           r.addVotes2();break;
       case 3:
           r.determineWinner();break;
       case 4:r.displayListOfCandidates();break;
       case 5:r.displayWinners();
           break;
       case 6: System.exit(0);
       }
      
   }
}

}

Add a comment
Know the answer?
Add Answer to:
Using JAVA You have been asked to write a program that can manage candidates for an...
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
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