我有以下代码:
import java.util.ArrayList;
public class TestCandidate2
{
public static void main(String[] args) {
ArrayList<Candidate> election = new ArrayList<Candidate>();
Candidate john = new Candidate("John Smith", 5000);
election.add(john);
Candidate mary = new Candidate("Mary Miller", 4000);
election.add(mary);
Candidate michael = new Candidate("Micheal Duffy", 6000);
election.add(michael);
Candidate tim = new Candidate("Tim Robinson", 2500);
election.add(tim);
Candidate joe = new Candidate("Joe Ashtony", 1800);
election.add(joe);
System.out.println("Results Per Candidate:");
System.out.println("________________________");
System.out.print("\n");
int totalVotes = 0;
int total = 0;
for(Candidate dec : election) {
System.out.println(dec.toString());
total += dec.getVotes();
totalVotes += dec.getVotes();
}
System.out.print("\n");
System.out.println("Total number of votes in election: " + totalVotes);
}
public static void printVotes(ArrayList<Candidate> table) {
for(int i = 0; i < table.size(); i++) {
System.out.println(table.size()[i]);
}
}
/**public static int getTotal(ArrayList<Candidate> table) {
int total = 0;
for(int i = 0; i < table.size(); i++) {
total = table[i].getVotes() + total;
}
return total;
}*/
/**public static void printResults(ArrayList<Candidate> table) {
double total = getTotal(table);
System.out.print("Candidate Votes Received % of Total Votes");
System.out.print("\n");
for(int i = 0; i < table.length; i++) {
System.out.printf("%s %17d %25.0f", table[i].getName(), table[i].getVotes(), ((table[i].getVotes() / total) * 100));
System.out.println("");
}
}*/
}
现在首先关闭我认为我应该得到的错误是需要arraylist,但是int找到&#39;,而是我得到的错误是需要的数组,但是找到int&#39 ;
我不知道我应该如何修复int i,因为每当我把[]声明为数组时我仍然会遇到错误。我尝试过研究,但似乎没有人有我的确切问题。
答案 0 :(得分:2)
您似乎未正确访问List
。而不是:
table[i].getVotes()
尝试:
table.get(i).getVotes();
或者完全避免使用索引。例如,您可以将getTotal()
重写为:
public static int getTotal(List<Candidate> candidates) {
int total = 0;
foreach (Candidate c : candidates) {
total += c.getVotes();
}
return total;
}
产生错误的行:
System.out.println(table.size()[i]);
有点令人困惑,但我想你想要:
System.out.println(table.get(i).getVotes());
答案 1 :(得分:1)
您可以使用List.get(int)
按位置获取元素(而不是数组的[]
)。另外,我建议你编程到列表界面。像
public static void printVotes(List<Candidate> table) {
for(int i = 0; i < table.size(); i++) {
System.out.println(table.get(i));
}
}
您还可以使用for-each
loop和+=
之类的
public static int getTotal(List<Candidate> table) {
int total = 0;
for(Candidate c : table) {
total += c.getVotes();
}
return total;
}
答案 2 :(得分:0)
您应该使用table.get(i)
代替table[i]
。这是ArrayList
而不是数组