【发布时间】:2019-05-21 20:20:04
【问题描述】:
我有课程课
public class Course implements Comparable<Course > {
private String nazwa;
private Integer lata;
private Teacher teacher;
private Student[] students;
public Course (String name, int years, int maxStudents, Teacher teacher) {
this.name = name;
this.years = years;
students = new Student[maxStudents];
this.teacher = teacher;
}
我不确定这样做是否正确
public void setTeacher(Teacher teacher)
{
this.teacher = teacher;
}
然后我有一些代码允许用户创建新课程。我先问一些基本信息
System.out.print("ask for name");
String name= scan.next();
System.out.print("ask for years");
int years= scan.nextInt();
System.out.print("ask for maxStudents");
int maxStudents = scan.nextInt();
我正在尝试将老师添加到新课程中。教师具有唯一 ID
Course course;
System.out.print("Choose teacher:\n");
teachers 是一个列表,包含所有教师
for(Teacher t : teachers)
{
System.out.print(t.getName() + " - " + t.getAcademicDeggre() +"\n");
}
course.setTeacher(Teacher ?);
courses.add(new Course(name, years, maxStudents, teacher?);
@解决方案:
int choice= scan.nextInt() - 1;
String ID= teachers.get(choice).getID();
Teacher teacher = getTeacherForCourse(teachers, ID);
【问题讨论】:
-
使用构造方法
-
setTeacher是一个 setter 方法,可让您在创建Course对象后随时设置教师。如果你想每次都和老师一起创建一个对象,让它成为构造函数的一部分 -
是的,但是如何从教师列表中获取具有特定ID的教师并将其放入课程构造函数
courses.add(new Course(name, years, maxStudents, teacher));