Skip to content
Advertisement

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

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.

JavaScript

Advertisement

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.

JavaScript

Demo

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement