我必须为我的班级创建一个程序,该程序创建一个选举候选者及其票数的数组,并遍历该数组以使用覆盖的toString方法打印每个候选者,然后打印具有每个名称,编号的表票数和总票数的百分比。我的问题是,它没有打印5个候选项中的每一个,而是将数组中的最后一个候选项打印了5次。这就是我所拥有的:
public class Candidate {
private String name;
private int numVotes;
public Candidate(String name, int numVotes){
this.name = name;
this.numVotes = numVotes;
}
public String getName(){
return name;
}
public int getNumVotes(){
return numVotes;
}
public String toString(){
return name + " has " + numVotes + " votes.";
}
}
public class TestCandidate {
public static void main (String[] args){
Candidate[] election = new Candidate[5];
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 Ashtony", 1800);
printVotes(election);
printResults(election);
}
public static void printVotes(Candidate[] list){
for (Candidate candidate : list){
System.out.println(candidate);
}
}
public static int getTotal(Candidate[] list){
int total = 0;
for (Candidate candidate : list){
total += candidate.getNumVotes();
}
return total;
}
public static void printResults(Candidate[] list){
System.out.printf("%-10s %20s %20s", "Candidate", "Votes Received", "% of Total Votes");
System.out.println();
for (Candidate candidate : list){
System.out.printf("%-10s %15s %15.2f", candidate.getName(), candidate.getNumVotes(), 100*(double)candidate.getNumVotes()/getTotal(list));
System.out.println();
}
System.out.print("Total number of votes in election: " + getTotal(list));
}
}
我正在寻找类似的输出内容:
John Smith has 5000 votes
Mary Miller has 4000 votes
...
Candidate Votes Recieved % of total votes
John Smith 5000 25.91
Mary Miller 4000 20.73
...
Total number of votes: 19300
但是我却得到了:
Joe Ashtony has 1800 votes
Joe Ashtony has 1800 votes
...(x3)
Candidate Votes Recieved % of total votes
Joe Ashtony 1800 20
Joe Ashtony 1800 20
...(x3)
Total number of votes: 9000