У меня есть домашнее задание, которое я должен закончить, но что-то в этом действительно беспокоит меня. Я думал об этом, но я думаю, что мой подход неверен. Ну, это действительно так, так как я попробовал это, и это просто дало мне что-то вроде исключения переполнения стека. Так или иначе, вот фрагмент спецификаций, которые мне дал наставник:
- Раздел определяется как комбинация учителя, предмета и
расписание.
- Секция может вместить до сорока (40) студентов.
- Каждый предмет стоит три (3) единицы. Учитель определяется
его / ее идентификатор факультета.
- Учитель не может преподавать две секции с одинаковым расписанием.
В моем классе учителей есть список разделов, которые он / она преподает. Я планировал, что если я создам раздел, конструктор должен сначала проверить, не совпадает ли расписание этого раздела с расписанием в списке. Если не было никакого конфликта, то раздел успешно создан, и этот раздел должен быть добавлен в список разделов, которые есть у учителя. Я думаю, моя логика в порядке, но моя реализация не так!
Вот класс, который я создал на основе приведенного выше описания:
import java.util.List;
import org.apache.commons.lang3.Validate;
public class Section {
//A section is defined as a combination of a teacher, a subject and a schedule.
private Teacher teacher;
private Subject subject;
private Schedule schedule;
private String sectionName;
//A section can accommodate a maximum of forty (40) students.
private int numOfStudentsItCanAccomodate = 40;
public Section(Teacher teacher, Subject subject, Schedule schedule,
String sectionName){
this.teacher = teacher;
this.subject = subject;
this.schedule = schedule;
this.sectionName = sectionName;
Validate.notNull(teacher,"Teacher field"+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notNull(subject,"Subject field"+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notNull(schedule,"Schedule field"+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notNull(sectionName,"Section name"+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notBlank(sectionName,"Section name"+Prompts.FAILED_PROMPT_BLANK.getMessage());
if(sectionConflictsWithTeachersOtherSections(teacher,schedule)==true){
throw new IllegalArgumentException(Prompts.FAILED_PROMPT_TEACHER.getMessage());
}else{
//**I believe this line faulty** No! It is faulty and stupid of me. T_T
teacher.addSection(new Section (teacher,subject,schedule,sectionName));
}
}
public Teacher getTeacher() {
return teacher;
}
public Subject getSubject() {
return subject;
}
public Schedule getSchedule() {
return schedule;
}
public String getSectionName() {
return sectionName;
}
//A teacher cannot teach two sections with the same schedule.
private boolean sectionConflictsWithTeachersOtherSections(Teacher teacher,Schedule newSchedule){
boolean conflict = false;
List<Section> teachersListOfSections = teacher.getListOfSections();
if(teacher.getListOfSections().size()>0){
for(Section takenSection:teachersListOfSections){
Schedule scheduleOfTakenSection = takenSection.getSchedule();
if(scheduleOfTakenSection.getDay().equals(newSchedule.getDay()) &&
scheduleOfTakenSection.getTime().equals(newSchedule.getTime())){
conflict = true;
}
}
}
return conflict;
}
public void subtractNumOfStudentsItCanAccomodate(){
this.numOfStudentsItCanAccomodate--;
}
public int getNumOfStudentsItCanAccomodate() {
return numOfStudentsItCanAccomodate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + numOfStudentsItCanAccomodate;
result = prime * result
+ ((schedule == null) ? 0 : schedule.hashCode());
result = prime * result
+ ((sectionName == null) ? 0 : sectionName.hashCode());
result = prime * result + ((subject == null) ? 0 : subject.hashCode());
result = prime * result + ((teacher == null) ? 0 : teacher.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Section other = (Section) obj;
if (numOfStudentsItCanAccomodate != other.numOfStudentsItCanAccomodate)
return false;
if (schedule == null) {
if (other.schedule != null)
return false;
} else if (!schedule.equals(other.schedule))
return false;
if (sectionName == null) {
if (other.sectionName != null)
return false;
} else if (!sectionName.equals(other.sectionName))
return false;
if (subject == null) {
if (other.subject != null)
return false;
} else if (!subject.equals(other.subject))
return false;
if (teacher == null) {
if (other.teacher != null)
return false;
} else if (!teacher.equals(other.teacher))
return false;
return true;
}
public boolean conflictsDayWith(Section newSection){
return (this.schedule.getDay().equals(newSection.schedule.getDay()));
}
public boolean conflictsTimeWith(Section newSection){
return (this.schedule.getTime().equals(newSection.schedule.getTime()));
}
}
Мой класс учителя:
public class Teacher extends Person{
private List<Section> listOfSections;
public Teacher(String firstName,String lastName, String middleName)
throws IllegalArgumentException{
this.firstName = firstName;
this.lastName = lastName;
this.middleName = middleName;
this.listOfSections = new ArrayList<Section>();
Validate.notNull(firstName, "First name "+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notNull(lastName, "Last name"+Prompts.FAILED_PROMPT_NULL.getMessage());
Validate.notNull(middleName, "Middle name"+Prompts.FAILED_PROMPT_NULL.getMessage());
}
public void addSectionToList(Section newSection){
listOfSections.add(newSection);
}
public void teachesSection(Section newSection){
this.listOfSections.add(newSection);
}
public List<Section> getListOfSections() {
return listOfSections;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((listOfSections == null) ? 0 : listOfSections.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Teacher other = (Teacher) obj;
if (listOfSections == null) {
if (other.listOfSections != null)
return false;
} else if (!listOfSections.equals(other.listOfSections))
return false;
return true;
}
@Override
public String toString(){
return firstName + " " + middleName + " " + lastName ;
}
}