如何在对象内创建数组? (Java)的

时间:2014-05-02 17:42:42

标签: java arrays object printing

我正在使用聚合和继承,我似乎无法弄清楚如何为单独的对象分别使用数组。通过这个例子,我将如何制作它,以便每个俱乐部拥有自己的一系列人员,以便我可以打印出俱乐部列表和属于每个俱乐部的成员。

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 个答案:

答案 0 :(得分: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++;
}