2014-05-02 163 views
0

我正在使用聚合和繼承,我似乎無法弄清楚如何爲單獨的對象有單獨的數組。在這個例子中,我將如何做到這一點,因此每個俱樂部都有自己的一系列人員,這樣我就可以列出俱樂部和屬於每個俱樂部的成員名單。你如何在一個對象內創建一個數組? (java)

public class Application{ 
    public static Club[] clubArray = new Club[10]; 

    //prompt user for club name 
    clubArray[x++] = new Club(name); 

    //prompt user for person name 
    Person newPerson = new Person(name); 
    clubArray[x-1].addPerson(newPerson); 
    personCount++; 

} 

public class Club{ 
    public Person[] personArray = new Person[100]; 

    //addPerson method 
    public void addPerson(Person newPerson){ 
      personArray[x] = newPerson; 
     } 
    } 
} 
+1

由同一用戶相關http://stackoverflow.com/questions/23432881/printing-out-objects-objects-stored-in-different-arrays-using-tostring-j – DoubleDouble

+1

這個問題所關注的代碼看起來很好,但其餘的代碼似乎缺少部分代碼。變量'x'和'i'從未聲明,例如,你從未見過使用personArray –

+0

這個問題可能在代碼中的其他地方。你在這裏得到的結果應該是每個'Club'實例都有自己的'personArray'實例。 –

回答

0

你不能把原始代碼就像你有它,你需要把它放在一個方法(或static block) -

public static Club[] clubArray = new Club[10]; 
public static int x = 0; // <-- init to 0. 

// You need a method... let's call it addClub. 
public static void addClub(String name, String personName) { 
    if (x >= clubArray.length) { 
    // Array is full. 
    return; 
    } 
    clubArray[x] = new Club(name); // <-- pass in the club name. 

    Person newPerson = new Person(personName); // <-- pass in the person name 
    clubArray[x].addPerson(newPerson); 
    personCount++; // <-- Not sure where you want this.... 
    x++; 
}