Candidate class:
public class Candidate
{
private static String name;
private static int numVotes;
Candidate(String name, int numVotes)
{
Candidate.name = name;
Candidate.numVotes = numVotes;
}
public String toString()
{
return name + " recieved " + numVotes + " votes.";
}
public static int getVotes()
{
return numVotes;
}
public static void setVotes(int inputVotes)
{
numVotes = inputVotes;
}
public static String getName()
{
return name;
}
public static void setName(String inputName)
{
name = inputName;
}
}
TestCandidate class:
public class TestCandidate
{
public static Candidate[] election = new Candidate[5];
public static void addCandidates(Candidate[] election)
{
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashton", 1800);
}
public static int getTotal(Candidate[] election)
{
int total = 0;
for (Candidate i : election)
{
total += Candidate.getVotes();
}
return total;
}
public static void printResults(Candidate[] election)
{
System.out.printf("%s%12s%25s", "Candidate", "Votes", "Percentage of Votes\n");
for (Candidate i: election)
{
System.out.printf("\n%s%10s%10s", Candidate.getName(), Candidate.getVotes(), ((double)Candidate.getVotes()/getTotal(election) * 100));
}
System.out.println("\n\nTotal Number of Votes: " + getTotal(election));
}
public static void main (String args[])
{
addCandidates(election);
printResults(election);
}
}
Whenever I run the TestCandidate class, it outputs this:
Candidate Votes Percentage of Votes
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Total Number of Votes: 9000
The point of the program is to output all of the candidates and calculate averages based on everyone. I believe it's an issue within my for-each loops. Any help with this would be appreciated.