2013-03-29 123 views
0

好的,所以我有一個非常簡單的我的計算機類的任務(它應該顯示通過數組和東西橫穿)。我不得不創建一個帶數組的版本和一個帶有arrayLists的版本,所以在測試者類中我有一些靜態方法,但是當我使用arrayList並且嘗試從對象所來自的類調用一個方法時(它是一個getter方法)我所得到的是一條錯誤消息,說它找不到。對象的ArrayList幫助java

這裏是我的代碼縮短版本:

進口的java.util。*; import 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."; 
} 

}

+0

嘗試替換此行election.add()= new Candidate(5000,「John Smith」);與election.add(新候選人(5000,「約翰史密斯」)); – Satya

+0

謝謝我相信這樣會更好,但我仍然收到「total + = election.getNumVotes();」的錯誤消息「我也試過「total + = election.get(b).getNumVotes();」和我靜靜地得到相同的錯誤信息「無法找到符號 - 方法getNumVotes()」 – user2223159

+0

你可能會發現我的教程[ArrayList的內部生活](http://volodial.blogspot.com/2013/07/internal-life -of-arraylist-in-java.html) –

回答

0

試試這個:

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); 
} 
} 
+0

YES!有用。謝謝你,謝謝你,謝謝你! – user2223159