各位大哥:
我在编译 一对多问题是报错:
想要的结果是:南京大学
南京大学
|- 学生姓名:小王 年龄:28 学校:南京大学
|- 学生姓名:大哥 年龄:36 学校:南京大学
|- 学生姓名:好人 年龄:25 学校:南京大学可是出来的是:
南京大学
C04.School@5224ee
|- 学生姓名:小王 年龄:28 学校:C04.School@5224ee
|- 学生姓名:大哥 年龄:36 学校:C04.School@5224ee
|- 学生姓名:好人 年龄:25 学校:C04.School@5224ee
不知道是什么原因啊?package C04;import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;class Student {
private String name;
private int age;
private School school;

public Student(String name,int age){
this.setName(name);
this.setAge(age);
}

public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public School getSchool(){
return school;
}
public void setSchool(School school){
this.school = school;
}

public String toString(){
return "学生姓名:" +this.name + " 年龄:" +this.age +" 学校:" + this.school;
}
}class School{
private String name;
private List<Student> allStudent;
public School(){
this.allStudent = new ArrayList<Student>();
}
public School(String name){
this();
this.setName(name);
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}

public List<Student> getAllStudent(){
return allStudent;
}
}
public class TestDemo01 {
public static void main(String[] args){
School sch = new School("南京大学");
Student st1 = new Student("小王",28);
Student st2 = new Student("大哥",36);
Student st3 = new Student("好人",25);

System.out.println(sch.getName());

sch.getAllStudent().add(st1);
sch.getAllStudent().add(st2);
sch.getAllStudent().add(st3);

st1.setSchool(sch);
st2.setSchool(sch);
st3.setSchool(sch);
System.out.println(sch);

Iterator<Student> iter = sch.getAllStudent().iterator();
while (iter.hasNext()){
System.out.println("\t|- "+iter.next());
}

}}

解决方案 »

  1.   

    哦 没问题
    你试试这样行不
    public class TestDemo01 { 
    public static void main(String[] args){ 
    School sch = new School("南京大学"); 
    Student st1 = new Student("小王",28); 
    Student st2 = new Student("大哥",36); 
    Student st3 = new Student("好人",25); System.out.println(sch.getName()); sch.getAllStudent().add(st1); 
    sch.getAllStudent().add(st2); 
    sch.getAllStudent().add(st3); st1.setSchool(sch); 
    st2.setSchool(sch); 
    st3.setSchool(sch); 
    System.out.println(sch.getName()); Iterator <Student> iter = sch.getAllStudent().iterator(); 
    while (iter.hasNext()){ 
    System.out.println("\t|- "+iter.next().getName()); 
    } } } 
      

  2.   

    sch 是一个School对象 不能直接打印 只能打印对象的name属性
    iter.next() 所指的也是一个School对象
      

  3.   

    原因是:
    我的Student 类和School 类不是public 的,但是我不知道怎么才能在Myeclipse 中把两个类编译呀?
    请大家帮帮忙!
      

  4.   

    不是自动编译的吗?看看你的classse文件里有没
      

  5.   


    谢谢你!
    我有测试了一下,
    也不是public 的问题,
    是我在School中加了toString 就可以了!
      

  6.   

    MyEclipse中不是保存自动编译吗 你直接run TestDemon就行了啊。System.out.println(sch.getName());return "学生姓名:" +this.name + " 年龄:" +this.age +" 学校:" + this.school.getName();   就能显示你要的了