Question

VotePersonalldentification -voterLastName:String voterFirstName:String -voterSIN: Integer voterAddress:String voterProvince:SUtilizing 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 main method using java

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

Main.java

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        // Initiate prompt message for the user
        System.out.println("Welcome to the newly built beta version of the voting system!");

        // Creation of a new object VotePersonalIndentificiation, in this case our 'voters' that are the
        // user that will input their information that will correspond with our private fields in that class
        VotePersonalIdentification voters = new VotePersonalIdentification();

        // Creation of a scanner to take user input
        Scanner scan = new Scanner(System.in);

        // Additional confirmation in case one of the fields were incorrect.
        // It uses a do while loop that will perform the task of asking for user input for their information
        // until all user input is validated as true and the final confirmation is agreed upon by the user.
        // This do-while loop contains a bunch of other do-while loops for each user input information.
        Boolean confirmation = false;
        do {

            // boolean declaration of 'check' to be used to validate user information.
            // string input is for the scanner, user input will be stored in this variable
            // int confirm is used in the last confirmation step in the switch case to verify
            // all user input is correct.
            Boolean check = false;
            String input;
            int confirm;

            // This do-while loop will take the user input(First Name) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your first name: ");
                input = scan.nextLine();
                check = voters.validateFirstName(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            voters.setVoterFirstName(input);

            // This do-while loop will take the user input(Last Name) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your Last name: ");
                input = scan.nextLine();
                check = voters.validateLastName(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            voters.setVoterLastName(input);

            // This do-while loop will take the user input(Address) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your address: ");
                input = scan.nextLine();
                check = voters.validateAddress(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            voters.setVoterAdress(input);

            // This do-while loop will take the user input(City) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your city: ");
                input = scan.nextLine();
                check = voters.validateCity(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            voters.setVoterCity(input);

            // This do-while loop will take the user input(Postal Code) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your postal code: ");
                input = scan.nextLine();
                check = voters.validatePostalCode(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            voters.setVoterPostalCode(input);

            // This do-while loop will take the user input(SIN) and store it into 'check' that will be used
            // to call the method 'validate' to validate the credentials of the user input
            // if user input matches the credentials listed in the validation method using regex
            // then and only then will the loop end
            do {
                System.out.println("Please enter your SIN (no spaces): ");
                input = scan.nextLine();
                check = voters.validateSIN(input);
                if (check == false) {
                    System.out.println("*** Error! Invalid input ***");
                }
            } while (check == false);
            int intString = Integer.parseInt(input);
            voters.setVoterSIN(intString);


            // This switch case is in the overall do-while loop and will act as a final confirmation
            // stage, as Although the validation method can catch credential error the methods cannot tell
            // user error such as a typo with names/address/etc. This is the final confirmation to ensure all
            // information is correct.
            // If there are error(s) then the whole do while loop will loop until this confirmation is true.
                System.out.println("Is following information correct? \n 1 = Yes, 2 = No");
                confirm = scan.nextInt();
                switch (confirm){
                    case 1:
                        confirmation = true;
                        voters.successfullyRegistered();
                        System.out.println("Your unique ID is "+voters.voterID());
                        break;
                    case 2:
                        System.out.println("Let's start over then!");
                        confirmation = false;
                        break;
                }
        } while (confirmation == false);

        // The creation of an obect array within the Candidate class
        // This uses the class that had inherited from Ballot > VotePersonalIdenficication.
        // These 5 arrays will act as candidates for the election/voting system.
        Candidate[] candidates = new Candidate[5];
        candidates[0]= new Candidate("John Cena", "You can't see me!, (Green Party)");
        candidates[1]= new Candidate("Leroy Jenkins", "LEEEEROOOOOYYYY JENNNKINSSS!, (Liberal Party)");
        candidates[2]= new Candidate("Aubrey Graham", "Musician turned politician, (New Democratic Party)");
        candidates[3]= new Candidate("Joe Rogen", "Original podcast pioneer, (PC Party)");
        candidates[4]= new Candidate("Justin Trudeau", "The second best Trudeau Prime Minister, (Liberal Party)");

        // A creation of a new object that will create a new ballot for the candidates above, needed to be created
        // after the declaration of the array candidates above.
        // This will create a ballot with the name 43rd Federal election and take the candidates array along with the voters.
        BallotCreation voteBallot = new BallotCreation(voters,"43rd Canadian Federal Election", candidates);

        // Using the object created above we can now use voteBallot to call a method within the same class
        // that being displayBallot which will display the candidates of the array stored into voteBallot above
        voteBallot.displayBallot();

        // This will prompt the user to submit a vote for the candidates printed above
        // By calling the methos submitBallot a case switch is executed to take user input
        System.out.println(voteBallot.submitBallot());

        // Confirmation message for the voter that their votes had been registered.
        System.out.println("Thank you " +voters.getVoterFirstName() +" "+voters.getVoterLastName() + ". Your vote has successfully been registered into our systems.");
    }
}

BallotCreation.java

import java.util.Scanner;

public class BallotCreation extends VotePersonalIdentification{

    // Private fields from the class diagram
    private String ballotName;
    private Candidate[] candidates = new Candidate[0];

    // No argument constrcutor
    BallotCreation(){
        this.ballotName="Ballot name";
        this.candidates= new Candidate[0];
    }


    // Constructor that takes the super of the super class
    BallotCreation(VotePersonalIdentification voters, String ballotName, Candidate[] candidates){
        this.ballotName=ballotName;
        this.candidates=candidates;
        super.setVoterLastName(voters.getVoterLastName());
        super.setVoterFirstName(voters.getVoterFirstName());
        super.setVoterAdress(voters.getVoterAdress());
        super.setVoterCity(voters.getVoterCity());
        super.setVoterPostalCode(voters.getVoterPostalCode());
        super.setVoterSIN(voters.getVoterSIN());
    }

    // Use to call & print the overwritten toString method
    public void displayBallot(){
        System.out.println(this.toString());
    }

    // This method is used to ask user input for the candidates they wish to vote for by
    // using a do while loop until 'i' which is just a condition based integer used to end the loop
    // is set to 1, whenever a valid vote is submitted. Otherwise will run until user inputs a valid vote.
    public String submitBallot() {
       Scanner userinput = new Scanner(System.in);
       int i = 0;
       do{
           System.out.println("Who would you like to vote for?\n[Vote by entering the number corresponding to the candidates]");
           int vote = userinput.nextInt();
       switch (vote) {
           case 0:
               System.out.println("You've voted for " + candidates[0]);
               i = 1;
               break;
           case 1:
               System.out.println("You've voted for " + candidates[1]);
               i = 1;
               break;
           case 2:
               System.out.println("You've voted for " + candidates[2]);
               i = 1;
               break;
           case 3:
               System.out.println("You've voted for " + candidates[3]);
               i = 1;
               break;
           case 4:
               System.out.println("You've voted for " + candidates[4]);
               i = 1;
               break;
           default:
               System.out.println("Invalid input! Try again.");
               break;
       }
       }while (i == 0);
       return "Thank you for your vote!";
    }

    // A toString method that is overwritten in candidate, this is used to display each of the candidates bio/names
    // to string and allows for print in string until the condition is met; end of candidates list.
    @Override
    public String toString(){
        String ballot = (this.ballotName + "\n");
        for (int i= 0; i < this.candidates.length; i++){
            ballot += ("\n"+ i +".)" + this.candidates[i].getCandidateName() + "\n[Biography]: " + this.candidates[i].getCandidateBiography()+"\n");
        }
        return ballot;
    }

    // Getters Setters for the private field of BallotCreation
    public void setBallotName(String ballotName){
        this.ballotName=ballotName;
    }
    public String getBallotName(){
        return ballotName;
    }
    public void setCandidates(Candidate[] candidates){
        this.candidates=candidates;
    }
    public Candidate[] getCandidates(){
        return candidates;
    }


}

Candidate.java

public class Candidate extends BallotCreation{

    // Private field from class diagram
    private String candidateName;
    private String candidateBiography;

    // An no arg constructor that takes super.
     Candidate(){
         super();
         this.candidateName="Leroy Jenkins";
         this.candidateBiography="Great voice";
    }

    // An argument constructor that is used to iniltalize the instance of the candidate class
    public Candidate(String candidateName, String candidateBiography){
         this.candidateName=candidateName;
         this.candidateBiography=candidateBiography;
    }

    // An toString method that overrides a method in BallotCreation. Used to display candidate's name.
    @Override
    public String toString(){
        return candidateName;
    }

    // Setters and getters of the private fields in this Candidate class
    public void setCandidateName(String candidateName){
         this.candidateName=candidateName;
    }
    public String getCandidateName(){
         return candidateName;
    }
    public void setCandidateBiography(String candidateBio){
         this.candidateBiography=candidateBio;
    }
    public String getCandidateBiography(){
         return this.candidateBiography;
    }

}

VotePersonalIdentification.java

public class VotePersonalIdentification {

    // Private fields from class diagram
    private String voterLastName, voterFirstName, voterAddress, voterCity, voterPostalCode;
    private int voterSIN;


    // An no argument constructor
    VotePersonalIdentification() {
        this.voterLastName = "Jenkins";
        this.voterFirstName = "Leroy";
        this.voterAddress = "1600 West Bank Drive";
        this.voterCity = "Peterborough";
        this.voterPostalCode = "K9J 0G2";
        this.voterSIN = 000000000;
    }

    // An arg constructor that is overloaded as their are two constructors. Used when initlized to given parameter value
    VotePersonalIdentification(String voterLastName, String voterFirstName, String voterAddress, String voterCity, String voterPostalCode, int voterSIN) {
        this.voterLastName = voterLastName;
        this.voterFirstName = voterFirstName;
        this.voterAddress = voterAddress;
        this.voterCity = voterCity;
        this.voterPostalCode = voterPostalCode;
        this.voterSIN = voterSIN;
    }

    // An override toString, where overwritten in the subclasses, returns/displays the voters credentials.
    @Override
    public String toString() {
        String vString = "Voter(s) Information: ";
        vString += ("First name: " + this.voterFirstName + "Last name: " + this.voterLastName + "Address: " + this.voterAddress + "City: " + this.voterCity + "Postal Code: " + this.voterPostalCode);
        return vString;
    }


    // ALL VALIDATION USED WITH REGEX TO VALIDATE FORMAT STRING OF THE VOTER'S INFORMATION.

    // In this validate method regex allows for alphabets a-z caps and lower case and -.
    public boolean validateFirstName(String voterFirstName) {
        return voterFirstName.matches("^[a-zA-Z-+']+$");
    }

    // In this validate method regex allows for a-z caps/uncaps and -.
    public boolean validateLastName(String voterLastName) {
        return voterLastName.matches("^[-a-zA-Z-]+$");
    }

    // In this validate method regex allows for lettera and numbers but must contain atleast one of each and allows for ., -.
    public boolean validateAddress(String voterAddress) {
        return voterAddress.matches("^(([a-zA-z]+.*[0-9]+.*)|[0-9]+.*([A-Za-z]+.*)([.\\w\\d]*))+$");
    }

    // In this validate method regex allows for digits&letters + whitespace, needs to be at least 6 characters long.
    // Assuming canadian postal codes.
    public boolean validatePostalCode(String voterPostalCode) {
        return voterPostalCode.matches("^[\\w\\s]{6,}+$");
    }

    // In this validate method regex allows for all letters and white spaces
    public boolean validateCity(String voterCity) {
        return voterCity.matches("^[a-zA-Z\\s]+$");
    }

    // In this validate method regex allows for all digits and needs to be 9 digits long.
    public boolean validateSIN(String voterSIN) {
        return voterSIN.matches("^[\\d+]{9,}+$");
    }

    // Just a message used to notify user that they have successfully registered.
        public String successfullyRegistered () {
            return "Successfully Registered";
        }

    // Should return a unique Id per voter starting at 1000 adding +1 for each new voter.
    public String voterID(){
        int counter = 1000;
        Integer unique = new Integer(counter);
        String uniqueID = unique.toString(counter++);
        return uniqueID;
    }


        // Setters and Getters for each of the private fields in this class.
        public void setVoterLastName (String voterLastName){
            this.voterLastName = voterLastName;
        }

        public String getVoterLastName () {
            return voterLastName;
        }

        public void setVoterFirstName (String voterFirstName){
            this.voterFirstName = voterFirstName;
        }

        public String getVoterFirstName () {
            return voterFirstName;
        }

        public void setVoterAdress (String voterAddress){
            this.voterAddress = voterAddress;
        }

        public String getVoterAdress () {
            return voterAddress;
        }

        public void setVoterCity (String voterCity){
            this.voterCity = voterCity;
        }

        public String getVoterCity () {
            return voterCity;
        }

        public void setVoterPostalCode (String voterPostalCode){
            this.voterPostalCode = voterPostalCode;
        }

        public String getVoterPostalCode () {
            return voterPostalCode;
        }

        public void setVoterSIN (Integer voterSIN){
            this.voterSIN = voterSIN;
        }

        public Integer getVoterSIN () {
            return voterSIN;
        }
    }

Add a comment
Know the answer?
Add Answer to:
Utilizing the class diagram above, implement the voting system. You will need a main method to...
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 using JAVA. You will need a main...

    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. VotePersonalldentification voterLastName:String voterFirstName:String...

  • 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...

  • In this assignment, you will implement Address and Residence classes. Create a new java project. Part...

    In this assignment, you will implement Address and Residence classes. Create a new java project. Part A Implementation details of Address class: Add and implement a class named Address according to specifications in the UML class diagram. Data fields: street, city, province and zipCode. Constructors: A no-arg constructor that creates a default Address. A constructor that creates an address with the specified street, city, state, and zipCode Getters and setters for all the class fields. toString() to print out all...

  • Ranked choice voting is a system of tallying election ballots that is used in many national...

    Ranked choice voting is a system of tallying election ballots that is used in many national and local elections throughout the world. Instead of choosing a single candidate, voters must rank the available candidates in the order of their choice. For example, if three candidates are available, a voter might choose #2, #1, and #3 as their choices, with #2 being their first choice, #1 the second, and #3 the third. The outcome is determined by a runoff, which follows...

  • Please help me with this code. Thank you Implement the following Java class: Vehicle Class should...

    Please help me with this code. Thank you Implement the following Java class: Vehicle Class should contain next instance variables: Integer numberOfWheels; Double engineCapacity; Boolean isElectric, String manufacturer; Array of integers productionYears; Supply your class with: Default constructor (which sets all variables to their respective default values) Constructor which accepts all the variables All the appropriate getters and setters (you may skip comments for this methods. Also, make sure that for engineCapacity setter method you check first if the vehicle...

  • An abstract class doesn't have a constructor (because you cannot make an object of the abstract...

    An abstract class doesn't have a constructor (because you cannot make an object of the abstract class). It should have at least one method, which then has to be overridden in all derived classes. Here is an example:   abstract void run();   class Honda4 extends Bike{   public static void main(String args[]){   obj.run();   } You are to create an abstract class called Shape, which has an abstract method called computeArea(). Derive a Circle class from Shape. (Circle is similar to your previous...

  • The current code I have is the following: package uml; public class uml {        public...

    The current code I have is the following: package uml; public class uml {        public static void main(String[] args) {              // TODO Auto-generated method stub        } } class Account { private String accountID; public Account(String accountID) { this.accountID = accountID; } public String getAccountID() { return accountID; } public void setAccountID(String accountID) { this.accountID = accountID; } @Override public String toString() { return "Account [accountID=" + accountID + "]"; } } class SuppliesAccount extends Account { private...

  • 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...

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