问题
I'm having the most difficult time trying to output a list of all clubs
and have the people
who are in that club
displayed under it, but it displays all people
for each club
instead. I know the problem lies within the nested for
loop because when it gets to the second for
loop, it goes to the personArray
with a new index value and prints out all the people. How do I get it so that it prints only the contents of clubArray[0]
, then for clubArray[1]
it will pick up where it left off in the personArray
and print clubArray[1]'s
people?
public class app {
public static Club[] clubArray = new Club[5];
public static int clubCount=0;
public static int personCount=0;
public static void main(String[] args) {
//inside a add method
//prompt user for club
clubArray[clubCount++] = new Club(clubName);
//prompt user for name, then prompt for Male or Female
if (x.equals("M")) {
Male newPerson = new Male(name);
clubArray[clubCount-1].addPerson(newPerson,personCount);
personCount++;
}
// .. in a print method
for(int x = 0; x < clubArray.length; x++) {
display+= clubArray[x].getClubName();
for(int y = 0; y < personCount; y++) {
display += clubArray[x].toString();
}
}
}
//--------------------------------
//data definition class
public class Club { //extend app?
public static Person[] personArray = new Person[200];
public void addPerson(Person newPerson, int personCount){
personArray[personCount] = newPerson;
}
public String toString() {
Person personObj = new Person();
String display= "";
return display = studentObj.getPersonName();
}
}
回答1:
The personArray
in Club
is declared static
, which means that there is only one person array, instead of one for each club, which is what you presumably want (each club has an array of all the people in that club).
It would almost certainly be better to have the club have a List<Person>
so that the list can grow as people are added to the club, instead of having a fixed size of 200 (unless you know that every club will always have exactly 200 people in it).
来源:https://stackoverflow.com/questions/23432881/printing-out-objects-within-objects-stored-in-different-arrays-using-tostring-j