我很难确定如何使用适当的课程对象显示共享personArray。例如,我需要显示课程列表和该课程中的人员,并再次显示下一个课程。我觉得我的嵌套for循环或personCount变量有问题,因为不是每个课程都有相同数量的人,所以我该怎么处理这个?
希望你们都能清楚地了解下面的精简代码。
注意*我必须使用聚合和toStrings,不允许使用列表,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();
}
}
答案 0 :(得分:0)
确保您的personArray中的所有50个人首先被初始化;检查它们是否通过打印出整个数组(你需要导入java.util.Arrays):
System.out.println(Arrays.toString(course[x].personArray));
如果这回复任何&#34; null&#34;那么你知道并非PersonArray中的每一个人都是先被初始化的。
答案 1 :(得分:0)
您应该将courseCount更改为courseArray.length,将personCount更改为courseArray.getPersonArraySize(),并在Course类中实现getPersonArraySize()以返回personArray的长度。
答案 2 :(得分:0)
用下面这些替换你的循环..
for (Course c : courseArray) {
print += c.getCourseName() + "\n";
for (Person p : c.personArray){
print += p.getPersonName()+ "\n";
}
}