【问题标题】:ArrayList of Objects help javaArrayList of Objects帮助java
【发布时间】:2013-03-29 03:50:08
【问题描述】:

好的,所以我有一个非常简单的计算机课作业(它应该显示遍历数组和东西)。我必须创建一个带有数组的版本和一个带有arrayLists的版本,所以在测试器类中我有一些静态方法,但是当我使用arrayList并尝试从对象所在的类中调用一个方法(它是一个getter方法) 我得到的只是一条错误消息,指出找不到它。

这是我的代码的缩短版本:

导入 java.util.*; 导入 java.util.List;

公共类testCandidate2 {

public static int getTotal(ArrayList election)
{
    int total = 0;
    for(int b = 0; b <election.size(); b++)
          total += election.getNumVotes();
    return total;
}


public static void main(String[] args)
{
    int totalVotes;
    List <Candidate> election = new ArrayList<Candidate>(5);
    election.add() = new Candidate(5000, "John Smith");

    totalVotes = getTotal(election);

}

}

公开课候选人 {

private String name;
private int numVotes;

Candidate(int nv, String n)
{
    name = n;
    numVotes = nv;
}

public String getName()
{
    return name;
}

public int getNumVotes()
{
    return numVotes;
}

public String toString()
{
    return name + " recieved " + numVotes + " votes.";
}

}

【问题讨论】:

  • 尝试替换这一行election.add() = new Candidate(5000, "John Smith"); withelection.add(new Candidate(5000, "John Smith"));
  • 谢谢,我确信这样会更好,但我仍然收到关于“total +=election.getNumVotes();”的错误消息我也试过“total +=election.get(b).getNumVotes();”我仍然收到相同的错误消息“找不到符号 - 方法 getNumVotes()”
  • 你可能会发现我在Internal life of ArrayList上的教程很有用

标签: arraylist


【解决方案1】:

试试这个:

import java.util.*;
//import java.util.List;

public class testCandidate2 {

public static int getTotal(ArrayList election)
{
    int total = 0;
    for(int b = 0; b <election.size(); b++)
         {
         Candidate ele = (Candidate) election.get(b);
       //  System.out.println(ele.getNumVotes());
         total += ele.getNumVotes();
         //System.out.println(o.getNumVotes());
    }
         //System.out.println( (Candidate) (election.get(b).getNumVotes());
          //.getNumVotes();
    return total;
}


public static void main(String[] args)
{
    int totalVotes;
    ArrayList <Candidate> election = new ArrayList<Candidate>(5);
    election.add(new Candidate(5000, "John Smith"));

    totalVotes = getTotal(election);
    System.out.println(totalVotes);
}
}

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2013-03-28
    • 2010-12-20
    • 2011-05-08
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2016-11-27
    相关资源
    最近更新 更多