University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Valg.java 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import java.util.Scanner;
  2. import java.util.HashMap;
  3. import java.io.*;
  4. class Party {
  5. private static int totalVotes = 0;
  6. private int nVotes = 0;
  7. public String name;
  8. Party(String n) {
  9. name = n;
  10. }
  11. public void addVote() {
  12. nVotes += 1;
  13. totalVotes += 1;
  14. }
  15. public int getVotes() {
  16. return nVotes;
  17. }
  18. public int getPercentage() {
  19. double percent = ((double)nVotes / (double)totalVotes) * 100;
  20. return (int)Math.round(percent);
  21. }
  22. }
  23. class Valg {
  24. public static void main(String[] args) throws IOException {
  25. Scanner file = new Scanner(new File("stemmer.txt"));
  26. String[] lines = new String[456];
  27. int i;
  28. HashMap<String, Party> parties = new HashMap<String, Party>();
  29. int totalVotes = 0;
  30. //Build array of line
  31. i = 0;
  32. while (file.hasNextLine()) {
  33. String line = file.nextLine();
  34. lines[i] = line;
  35. i += 1;
  36. }
  37. //Go through the array, adding votes to parties
  38. for (i = 0; i < lines.length; ++i) {
  39. String line = lines[i];
  40. //Create the party if it doesn't exist yet
  41. if (!parties.containsKey(line))
  42. parties.put(line, new Party(line));
  43. //Add a vote to the party
  44. parties.get(line).addVote();
  45. }
  46. //Loop through the parties, printing their results and get the winner
  47. Party winner = null;
  48. for (Party p: parties.values()) {
  49. if (winner == null)
  50. winner = p;
  51. if (p.getVotes() > winner.getVotes())
  52. winner = p;
  53. System.out.println(
  54. p.name+" got "+p.getVotes()+" votes, or "+
  55. p.getPercentage()+" percent of all the votes."
  56. );
  57. }
  58. System.out.println(winner.name+" got the most votes.");
  59. }
  60. }