0

I'm working with aggregation and inheritance and I can't seem to figure out how to have separate arrays for separate objects. With this example, how would I make it so each club has it's own array of people so that I can print out a list of clubs and the members which belong to each.

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;
        }
    }
}
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
  • 1
    related by same user http://stackoverflow.com/questions/23432881/printing-out-objects-within-objects-stored-in-different-arrays-using-tostring-j – DoubleDouble May 02 '14 at 17:44
  • 1
    The code to which this question is about seems fine, but the rest seems to have parts missing. Variables `x` and `i` are never declared for example and you never seen to use the personArray – Richard Tingle May 02 '14 at 17:46
  • The problem likely lies somewhere else in your code. What you have here should result in each `Club` instance having its own `personArray` instance. – Mike B May 02 '14 at 17:46
  • Are you receiving some type of error message or just not seeing what is expected? – DoubleDouble May 02 '14 at 17:48

1 Answers1

0

You can't place raw code like you had it, you need to put it in a method (or a 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++;
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249