我正在尝试输出所有俱乐部的列表以及为每个俱乐部输入的人员,但是它会单独显示每个俱乐部(即有一个俱乐部和该俱乐部的人员列表,然后是第二个俱乐部进入和那个人等等)
我想确保向每个数组添加对象是正确的,并确定我的toString()
方法应该是什么样子。
到目前为止,这是我的代码:
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;
}
}
答案 0 :(得分:0)
您可以使用嵌套for循环
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();
}
}
我不确定你的课程是否以这种方式设置,但你明白了。只需在外部for循环中一次遍历1个俱乐部,内循环遍历该俱乐部中的每个人。
答案 1 :(得分:0)
personArray不应该是静态的。如果它是静态的,则所有Club实例将共享相同的人群。最好使用List而不是静态数组。
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();
}
}
班主任:
public class Person
{
private String name;
private boolean male;
public Person( String name, boolean male)
{
this.name = name;
this.male = male;
}
public String toString() { ... }
}
班级应用:
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);
}
}