【发布时间】:2014-05-04 19:15:59
【问题描述】:
我很难弄清楚如何使用适当的课程对象显示共享的 personArray。例如,我需要显示一门课程的列表以及该课程中的人员,并再次显示下一门课程。我觉得我的嵌套 for 循环或 personCount 变量有问题,因为并非每门课程的人数都相同,我该如何处理?
希望大家可以清楚地了解下面的精简代码。
注意*我必须使用aggregation和toStrings,不允许使用lists、arraylists或scanner。
谢谢!
public class School {
private static Course[] courseArray = new Course[5];
public static void printList(){
String print = "";
for (int x = 0; x < courseCount; x++) {
print += courseArray[x].getCourseName() + "\n";
for (int y = 0; y < personCount; y++){
print += courseArray[y].personArray[y].getPersonName()+ "\n";
//^ I thought I could use the 1st forloop index to stay in the 1 course and print out all the people for that course(like the hardcode example below) but I get a nullpointer
}
}
JOptionPane.showMessageDialog(null,print);
/*
If I hardcode the print String like below I get the correct output.
So I know my objects are being stored properly, but I can't figure out how to get the correct display with a loop
print += courseArray[0].personArray[0].getPersonName(); //tim (bio)
print += courseArray[0].peopleArray[1].getPersonName(); //bob (bio)
print += courseArray[1].peopleArray[2].getPersonName(); //john (art)
*/
}
}
------------------------
public class Course {
private Person[] personArray = new Person[50];
//constructor for course
// get/set courseName methods
public String toString(){
// not sure how to use this the right way
}
}
-----------------------------------
public class Person extends Course {
//constructor for person
// get/set personName methods
public String toString(){
return getPersonName();
}
}
【问题讨论】:
标签: java arrays object printing tostring