How to find out user votes and winner of election code? [closed]

Tags:



I can’t seem the get the right amount of votes for the user inputted name and I can’t figure out how to get the most popular name declared as the winner. I do get how many times I’ve voted for someone but it’s not always right. Sometimes I get an ArrayIndexOutOfBounds Exception error and I think it has to do something with the Candidate get and Vote get print in the end.

This is how it supposed to be.

This is how it supposed to be.

That’s how I managed to do it so far.

Thats how I managed to do it so far.

public class JavaApplication16 {

    public static void main(String[] args) {


        ArrayList<String> Names = new ArrayList<String>();

        ArrayList<Integer> Votes = new ArrayList<Integer>();
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the name you wish to vote for: ");
        String addName = input.nextLine();

        while (addName.length() != 0) {
            if (Names.contains(addName)) { // Name already in the array
                int i = Names.indexOf(addName); // Add some code to find the index of the name in the Names array
                Integer j = Votes.get(i);   // Find out how many votes they currently have
                j++;    // Increment it by 1
                Votes.set(i, j); // Put the new number of votes back into the Votes array at the correct index
                //Votes.indexOf(addName);// Increment the contents of the Votes array at the same index

                //break;
            }
            if (addName.equals("-0")) {
                System.out.println("List of the Candidates");
                break;

            } else { // Name not in the array
                Names.add(addName); // Add the name to the end of the list
                Votes.add(1); // They have one vote so far, so set their vote count to 1
            }

            addName = input.nextLine();

        }
        //End of the while loop to vote

        //A List to remove the duplicates from the Name list
        ArrayList<String> Candidate = new ArrayList<String>();
        for (String nam : Names) {
            if (!Candidate.contains(nam)) {
                Candidate.add(nam);
            }
        }

        for (int t = 0; t < Candidate.size(); t++) {

        }
        for (int i = 0; i < Names.size(); i++) {

        }
        for (int j = 0; j < Votes.size(); j++) {

        }  // The following is a basic example - you could use a for loop and make the output look better

        System.out.println(Candidate.get(0) + " recieved " + (Votes.get(0) + " vote. "));
        System.out.println(Candidate.get(1) + " recieved " + (Votes.get(1) + " vote. "));
        System.out.println(Candidate.get(2) + " recieved " + (Votes.get(2) + " vote. "));
        System.out.println(Candidate.get(3) + " recieved " + (Votes.get(3) + " vote. "));


        // Code to find out the highest amount of votes
        System.out.println("AND THE WINNER IS");
        System.out.println(Collections.max(Names));
        System.out.println(Collections.max(Votes));

    }
}

Answer

You use illegal data stryctyre for your goal. You use List, but you have to count the votes for each name. So you have to use Map<String, Integer> where key is the name and value is the amount of votes.

Additionally, you have to sort these names by votes. So you could create a new list with all entries form this map and then sort these names by votes desc. But I prefer to use another data structure PriorityQueue tha internally sorts the entries.

public static void main(String... args) {
    System.out.println("#######################################");
    System.out.println("# Enter the votes, one vote per line. #");
    System.out.println("# End with either -1 or an empty line.#");
    System.out.println("#######################################");
    System.out.println();

    Scanner scan = new Scanner(System.in);
    Map<String, Integer> votes = new HashMap<>();

    while (true) {
        String name = scan.nextLine().trim();

        if (name.isEmpty() || "-1".equals(name))
            break;

        votes.put(name, votes.getOrDefault(name, 0) + 1);
    }

    if (votes.isEmpty())
        System.out.println("No Votes.");
    else {
        final Comparator<Map.Entry<String, Integer>> sortByVotesDesc = (one, two) -> Integer.compare(two.getValue(), one.getValue());
        Queue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(sortByVotesDesc);
        queue.addAll(votes.entrySet());

        Map.Entry<String, Integer> winner = queue.element();

        while (!queue.isEmpty()) {
            Map.Entry<String, Integer> vote = queue.remove();
            System.out.format("%s received %d votesn", vote.getKey(), vote.getValue());
        }

        System.out.println("------------------------");
        System.out.format("The Winner is %s with %d votesn", winner.getKey(), winner.getValue());
    }
}

Demo

#######################################
# Enter the votes, one vote per line. #
# End with either -1 or an empty line.#
#######################################

Sam
Peter
James
Sam
Sam
Peter
Sam

Sam received 4 votes
Peter received 2 votes
James received 1 votes
------------------------
The Winner is Sam with 4 votes


Source: stackoverflow