gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:58:01 25 4
gpt4 key购买 nike

我有以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com