java - 需要数组(列表?),但 int 发现错误

标签 java arrays

我有以下代码:

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("");
    }
}*/
}

现在,我认为我应该得到的错误是“需要数组列表,但找到了整数”,但我得到的错误是“需要数组,但找到了整数”。

我不知道应该如何修复 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());

关于java - 需要数组(列表?),但 int 发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061548/

相关文章:

java - @OnDelete(CASCADE) 不适用于双向映射( hibernate )

c++ - 重载分辨率和数组 : which function should be called?

java - Android:如何将变量应用于 toast ?

javascript - 使用 Javascript 数组(或对象)的单位转换器

arrays - 在Matlab中将矩阵中的元素i,j设置为i^j

java - 修改java中的数组

java - Hive Java UDTF错误:ArrayIndexOutofBounds:1

javascript - 在 JavaScript 中读取 TIFF 文件的响应

java - 如何从 aws s3bucket android 删除文件?

java - Maven - 从 JAR 文件加载资源?