创建新课程时,我应该如何将其添加到新课程中?

时间:2019-05-21 20:20:05

标签: java set add subclass

我有课程课

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");

老师是一个列表,其中包含所有老师

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);

2 个答案:

答案 0 :(得分:1)

  1. 定义教师与课程之间的关系
    • 您将老师添加到了课程中,但是对我而言,没有老师就不会存在该课程,因此老师应该有一个课程列表(但这可能超出范围)
  2. 从用户那里获取有关新课程的信息
  3. 确定课程的老师
  4. 创建课程

第3步

private Teacher getTeacherForCourse(List<Teacher> teachers, long id) {
    for(Teacher teacher : teachers)
    {
        // Return the teacher if match the criteria
        if(teacher.getId() == id)
        {
            return teacher;
        }
    }
    return null; // or throw exception
}

或者使用Java 8

private Optional<Teacher> getTeacherForCourse(List<Teacher> teachers, long id) {
    return teachers.stream()
            .filter(teacher -> teacher.getId() == id)
            .findFirst();
}

第4步

Teacher teacher = getTeacherForCourse(teachers, 9454);
courses.add(new Course(name, years, maxStudents, teacher);

基本上,您可以在创建时通过构造函数设置属性

courses.add(new Course(name, years, maxStudents, teacher));

或者由二传手创建后

Course course = new Course();

course.setName(name);
course.setYears(years);
course.setMaxSturdents(maxStudents);
course.setTeacher(teacher);

courses.add(course);

或组合

答案 1 :(得分:0)

最后一个问题,为什么.getID被忽略?老师有ID属性,也就是字符串。

我要打印每位老师

for(int i = 0; i < teachers.size(); i++){
   System.out.print(i + teachers.get(i).getName() + " " + teachers.get(i).getSurName() + " - " + teachers.get(i).getAccademicDeggre());
  }

然后用户按编号选择要添加到课程中的老师

int choise = scan.nextInt();

接下来我要从列表中具有该索引的老师那里获取ID

teachers.get(choise).getID();
相关问题