[英]Array (list?) required, but int found error
我有以下代码:
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 required,但是int found',但是我得到的错误是'数组需要,但是找到了int'。
我不知道我应该如何修复int i,因为无论什么时候我把[]声明为数组,我仍然会得到错误。 我尝试过研究,但似乎没有人有我的确切问题。
您似乎错误地访问了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());
您可以使用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
循环和+=
like,
public static int getTotal(List<Candidate> table) {
int total = 0;
for(Candidate c : table) {
total += c.getVotes();
}
return total;
}
你应该使用table.get(i)
而不是table[i]
。 这是一个ArrayList
而不是一个数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.