|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import java.util.Scanner;
- import java.util.HashMap;
- import java.io.*;
-
- class Party {
- private static int totalVotes = 0;
- private int nVotes = 0;
-
- public String name;
-
- Party(String n) {
- name = n;
- }
-
- public void addVote() {
- nVotes += 1;
- totalVotes += 1;
- }
-
- public int getVotes() {
- return nVotes;
- }
-
- public int getPercentage() {
- double percent = ((double)nVotes / (double)totalVotes) * 100;
- return (int)Math.round(percent);
- }
- }
-
- class Valg {
- public static void main(String[] args) throws IOException {
- Scanner file = new Scanner(new File("stemmer.txt"));
- String[] lines = new String[456];
- int i;
-
- HashMap<String, Party> parties = new HashMap<String, Party>();
- int totalVotes = 0;
-
- //Build array of line
- i = 0;
- while (file.hasNextLine()) {
- String line = file.nextLine();
- lines[i] = line;
- i += 1;
- }
-
- //Go through the array, adding votes to parties
- for (i = 0; i < lines.length; ++i) {
- String line = lines[i];
-
- //Create the party if it doesn't exist yet
- if (!parties.containsKey(line))
- parties.put(line, new Party(line));
-
- //Add a vote to the party
- parties.get(line).addVote();
- }
-
- //Loop through the parties, printing their results and get the winner
- Party winner = null;
- for (Party p: parties.values()) {
- if (winner == null)
- winner = p;
-
- if (p.getVotes() > winner.getVotes())
- winner = p;
-
- System.out.println(
- p.name+" got "+p.getVotes()+" votes, or "+
- p.getPercentage()+" percent of all the votes."
- );
- }
-
- System.out.println(winner.name+" got the most votes.");
- }
- }
|