除最后一列数据输出外,此代码可生成准确的输出。
输出旨在显示候选人的非十进制投票百分比值。
我的逻辑错误导致上述值打印为0。
输出如下:
public class Candidate {
public String name;
public 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 getName() + " received " + getNumVotes() + " votes.";
}
}
import java.util.*;
public class TestCandidate {
public static void main(String [] args) {
ArrayList<Candidate> list = new ArrayList<Candidate>();
list.add(new Candidate("John Smith", 5000));
list.add(new Candidate("Mary Miller", 4000));
list.add(new Candidate("Michael Duffy", 6000));
list.add(new Candidate("Tim Robinson", 2500));
list.add(new Candidate("Joe Ashtony", 1800));
System.out.println("Results per candidate:");
System.out.println("______________________\n");
int total = getTotal(list);
printVotes(list);
System.out.print("\nCandidate\t\tVotes Received\t\t% of Total Votes");
printResults(list);
System.out.println("\n\nTotal number of votes in election: " + total);
}
public static void printResults(ArrayList<Candidate> list) {
String name = "";
int percent = 0;
int votes = 0;
int total = getTotal(list);
for(Candidate token : list) {
name = token.getName();
votes = token.getNumVotes();
percent = (votes / total) * 100;
System.out.printf("\n%1s\t%12d\t%17d", name, votes, percent);
}
}
public static void printVotes(ArrayList<Candidate> list) {
for(Candidate token : list) {
System.out.println(token);
}
}
public static int getTotal(ArrayList<Candidate> list) {
int total = 0;
for(Candidate token : list) {
total += token.getNumVotes();
}
return total;
}
}
答案 0 :(得分:4)
您正在此处执行整数除法。
percent = (votes / total) * 100;
votes
总是比total
更低或更低,因此votes/total
可能会因整数除法而导致0。
将percent
更改为double
并将分部的操作数之一强制转换为double
,或者如果要将percent
保留为整数,则乘以{{ 1}}先用100然后除以vote
。
total