Java 遍历数组
我必须为我的类创建一个程序,该程序创建一个选举候选人及其投票数数组,并遍历该数组,使用重写的toString方法打印每个候选人,然后打印一个包含每个名称、投票数和总投票数百分比的表。我的问题是,它不是打印5个候选对象中的每一个,而是打印数组中的最后一个候选对象5次。这就是我所拥有的:Java 遍历数组,java,arrays,traversal,Java,Arrays,Traversal,我必须为我的类创建一个程序,该程序创建一个选举候选人及其投票数数组,并遍历该数组,使用重写的toString方法打印每个候选人,然后打印一个包含每个名称、投票数和总投票数百分比的表。我的问题是,它不是打印5个候选对象中的每一个,而是打印数组中的最后一个候选对象5次。这就是我所拥有的: public class Candidate { private String name; private int numVotes; public Candidate(String na
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
不能复制。尝试一个干净的构建。我打赌
Candidate
字段最初是static
。您的代码看起来很好-我认为您的IDE正在干扰您。System.out.print(“选举中的总票数:”+getTotal(list));应该是println而不是print。另外,尝试在printResults开始时获取一次总数,而不是每个候选人一次(您不希望它在迭代过程中发生变化)。