问题
I'm trying to output a list of all the clubs along with the people entered for each club, but have it display each club individually (i.e. there is one club and the list of people for that club, then the second club entered and the people for that one and so on)
I wanted to make sure the adding of objects to each array was correct and figure out what my toString()
method should look like.
Here's my code so far:
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++;
}
}
//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;
}
}
回答1:
You can use a nested for loop
for(int x = 0; x < clubArray.length; x++) {
System.out.println(clubArray[x].getName();
for(int y = 0; y < clubArray[x].getPeople.length; y++) {
System.out.println(clubArray[x].getPeople[y].getName();
}
}
I am not sure if your classes are set up this way, but you get the idea. Just iterate through 1 club at a time in the outer for loop, and for the inner loop iterate through each person in that club.
回答2:
The personArray should not be static. If it is static all the Club instances will share the same array of people. It is better to use List instead of static arrays.
public class Club {
String name;
List<Person> people = new LinkedList<>();
public Club(String name) { this.name = name; }
public void addPerson(Person p)
{
people.add(p);
}
public int countPeople()
{
return people.size();
}
public String toString()
{
StringBuilder sb = new StringBuilder("Club name:").append(name);
for(Person p : people)
sb.append(p).append(" ");
return sb.toString();
}
}
Class Person :
public class Person
{
private String name;
private boolean male;
public Person( String name, boolean male)
{
this.name = name;
this.male = male;
}
public String toString() { ... }
}
Class App :
public class App
{
List<Club> clubs = new ArrayList<>();
public void addClub(Club club)
{
clubs.add(club);
}
public String toString()
{
StringBuilder sb = new StringBuilder();
for(Club c : clubs)
sb.append(c);
return sb.toString();
}
public static void main(String[] args)
{
App app = new App();
Club club1 = new Club("ClubName1");
club1.add(new Person("George", true));
club1.add(new Person("Mary", false));
app.addClub(club1);
Club club2 = new Club("ClubName2");
club2.add(new Person("Jacob", true));
club2.add(new Person("Katie", false));
app.addClub(club2);
System.out.println(app);
}
}
来源:https://stackoverflow.com/questions/23429536/how-to-print-contents-from-2-different-arrays-and-have-items-grouped