CS102/enrolment
Report
enrolment›src›schoolcourseenrolmentsystem›dataManager.java

singleton class· schoolcourseenrolmentsystem

dataManager.java

dataManager is the only place the program reads and writes files. It keeps the five in-memory lists, loads them from pipe-delimited text files at start-up and writes them back.

public class dataManager
Pattern
Singleton via synchronized getInstance()
Delimiter
| (pipe), lists use commas
Files
students, instructors, administrators, courses, assessments
Missing file
Prints a message and starts with an empty list

Responsibilities#

  • Load all data at start-up and save it on exit
  • Hold the single copy of every list
  • Add, remove and look up students, instructors, admins, courses and grades
  • Keep IDs and course codes unique
  • Enrolment statistics and the most-popular-course report

Fields & enums#

TypeNameModifiersLine
dataManagerinstanceprivate staticL8
List<Instructor>instructorsprivateL11
List<Administrator>administratorsprivateL12
List<Student>studentsprivateL13
List<Course>coursesprivateL14
List<Assessment>gradesprivateL15
StringSTUDENTS_FILEprivate static finalL19
StringINSTRUCTORS_FILEprivate static finalL20
StringADMINISTRATORS_FILEprivate static finalL21
StringCOURSES_FILEprivate static finalL22
StringASSESSMENTS_FILEprivate static finalL23
StringDELIMITERprivate static finalL24

Constructors#

  • dataManager()DefaultL27

    Package-private constructor: creates the five empty lists and prints “Testing Constructor”. Use getInstance() instead.

1 method

Singleton#

  • dataManager getInstance()staticL36

    Create the single instance on first use and return it afterwards.

12 methods

Load & save#

  • void loadAllData()packageL44

    Load students, instructors, administrators, courses, then assessments.

    • Students load before courses, so saved course codes cannot be resolved (see Known issues)
  • void saveAllData()L53

    Write all five lists back to their files.

  • void loadStudents()privateL63

    Read students.txt. Each line needs at least 7 fields.

    • Prints every line it loads
  • void saveStudents()packageL107

    Write students.txt, joining enrolled course codes with commas.

  • void loadInstructors()privateL136

    Read instructors.txt. Each line needs at least 6 fields.

  • void saveInstructors()packageL162

    Write instructors.txt.

  • void loadAdministrators()privateL181

    Read administrators.txt. Each line needs at least 6 fields.

  • void saveAdministrators()privateL206

    Write administrators.txt.

  • void loadCourses()privateL225

    Read courses.txt, resolving instructor and student IDs. Each line needs at least 8 fields.

  • void saveCourses()packageL267

    Write courses.txt, joining enrolled student IDs with commas.

  • void loadAssessments()privateL299

    Read assessments.txt. Each line needs at least 5 fields.

  • void saveAssessments()privateL325

    Write assessments.txt.

4 methods

Students#

  • void addStudent(Student student)L342

    Add if the ID is unique, then save students.txt.

  • boolean removeStudent(String studentId)L356

    Remove by ID, then save students.txt.

  • Student getStudentById(String studentId)L372

    Look up a student, or null.

  • List<Student> getAllStudents()L381

    The live student list.

4 methods

Instructors#

  • void addInstructor(Instructor instructor)L386

    Add if the ID is unique, then save instructors.txt.

  • boolean removeInstructor(String instructorId)L401

    Remove by ID, clear it from any course it taught, then save both files.

  • Instructor getInstructorById(String instructorId)L422

    Look up an instructor, or null.

  • List<Instructor> getAllInstructors()L431

    The live instructor list.

3 methods

Administrators#

  • void addAdministrator(Administrator admin)L437

    Add if the ID is unique, then save administrators.txt.

    • Called at start-up to register the default admin
  • Administrator getAdminById(String adminId)L451

    Look up an administrator, or null.

  • List<Administrator> getAllAdministrators()L460

    The live administrator list.

4 methods

Courses#

  • void addCourse(Course course)L465

    Add if the course code is unique.

  • boolean removeCourse(String courseCode)L481

    Remove a course by code.

  • Course getCourseByCode(String courseCode)L500

    Look up a course, or null.

  • List<Course> getAllCourses()L509

    The live course list.

4 methods

Assessments#

  • void addAssessment(Assessment assessment)L514

    Add a grade record.

  • void updateAssessment(String studentId, String courseCode, Assessment.ExamType examType, double score)L524

    Update a matching grade or record a new one.

  • List<Assessment> getAssessmentsByStudentAndCourse(String studentId, String courseCode)L542

    Every grade for one student in one course.

  • List<Assessment> getAllAssessments()L553

    The live grade list.

4 methods

Uniqueness#

  • boolean isStudentIdUnique(String studentId)privateL558

    No student already has this ID.

  • boolean isInstructorIdUnique(String instructorId)privateL562

    No instructor already has this ID.

  • boolean isAdminIdUnique(String adminId)privateL565

    No administrator already has this ID.

  • boolean isCourseCodeUnique(String courseCode)privateL569

    No course already has this code.

6 methods

Operations & reports#

  • void assignInstructorToCourse(String courseCode, String instructorId)L574

    Assign by course code and instructor ID, then save courses.

  • void enrollStudentInCourse(String studentId, String courseCode)L599

    Enrol by IDs and save both files if it worked.

  • void dropStudentFromCourse(String studentId, String courseCode)L618

    Drop by IDs and save both files if it worked.

  • void closeCourse(String courseCode)L639

    Close a course by code and save courses.

  • void viewEnrollmentStatistics()L657

    Per-course counts, total enrolled, and whether any course is open.

  • void generateReports()L676

    Print the most popular course, or “No enrollments found.”

Known issues#

Source

dataManager.java696 lines · from the project report
1package schoolcourseenrolmentsystem;
2
3import java.io.*;
4import java.util.*;
5
6public class dataManager {
7
8 private static dataManager instance = null;
9
10 // Main data lists
11 private List<Instructor> instructors;
12 private List<Administrator> administrators;
13 private List<Student> students;
14 private List<Course> courses;
15 private List<Assessment> grades;
17 // File paths
19 private static final String STUDENTS_FILE = "students.txt";
20 private static final String INSTRUCTORS_FILE = "instructors.txt";
21 private static final String ADMINISTRATORS_FILE = "administrators.txt";
22 private static final String COURSES_FILE = "courses.txt";
23 private static final String ASSESSMENTS_FILE = "assessments.txt";
24 private static final String DELIMITER = "\\|";
26 // Private constructor to prevent instantiation
27 dataManager() {
28 instructors = new ArrayList<>();
29 administrators = new ArrayList<>();
30 students = new ArrayList<>();
31 courses = new ArrayList<>();
32 grades = new ArrayList<>();
33 System.out.println("Testing Constructor");
34 }
36 public static synchronized dataManager getInstance() {
37 if (instance == null) {
38 instance = new dataManager();
39 }
40 return instance;
41 }
43 // Load all data from files
44 void loadAllData() {
45 loadStudents();
46 loadInstructors();
47 loadAdministrators();
48 loadCourses();
49 loadAssessments();
50 }
52 // Save all data to files
53 public void saveAllData() {
54 saveStudents();
55 saveInstructors();
57 saveAdministrators();
58 saveCourses();
59 saveAssessments();
60 }
62 // Load Students from file
63 private void loadStudents() {
64 try (BufferedReader reader = new BufferedReader(new FileReader(STUDENTS_FILE))) {
65 String line;
66 while ((line = reader.readLine()) != null) {
67 System.out.println("Loading student: " + line);
68 String[] parts = line.split(DELIMITER);
69 if (parts.length >= 7) {
70 String name = parts[0];
71 String id = parts[1];
72 String password = parts[2];
73 String email = parts[3];
74 String phoneNumber = parts[4];
75 String address = parts[5];
76 int creditLimit = Integer.parseInt(parts[6]);
78 List<Course> enrolledCourses = new ArrayList<>();
80 if (parts.length > 7 && !parts[7].isEmpty()) {
81 String[] courseCodes = parts[7].split(",");
82 for (String code : courseCodes) {
83 Course course = getCourseByCode(code.trim());
84 if (course != null) {
85 enrolledCourses.add(course);
86 }
87 }
88 }
89 Student student = new Student(name, id, password, email, phoneNumber, address,
90 creditLimit,enrolledCourses);
91 System.out.println(student);
92 if (isStudentIdUnique(id)) {
93 students.add(student);
95 }
96 }
97 }
98 } catch (FileNotFoundException e) {
99 System.out.println("Students file not found. Starting with empty student list.");
100 } catch (IOException e) {
101 System.out.println("Error reading students file: " + e.getMessage());
102 } catch (NumberFormatException e) {
103 System.out.println("Error parsing student data: " + e.getMessage());
104 }
105 }
106 // Save Students to file
107 void saveStudents() {
108 try (BufferedWriter writer = new BufferedWriter(new FileWriter(STUDENTS_FILE))) {
109 for (Student student : students) {
110 StringBuilder courseCodes = new StringBuilder();
111 for (Course course : student.getEnrolledCoursesList()) {
112 if (courseCodes.length() > 0) {
113 courseCodes.append(",");
114 }
115 courseCodes.append(course.getCourseCode());
116 }
117 String line = String.join("|",
118 student.getName(),
119 student.getId(),
120 student.getPassword(),
121 student.getEmail(),
122 student.getPhoneNumber(),
123 student.getAddress(),
124 String.valueOf(student.getCreditLimit()),
125 courseCodes.toString());
126 writer.write(line);
127 writer.newLine();
128 }
129 } catch (IOException e) {
130 System.out.println("Error writing students file: " + e.getMessage());
131 }
133 }
135 // Load Instructors from file
136 private void loadInstructors() {
137 try (BufferedReader reader = new BufferedReader(new FileReader(INSTRUCTORS_FILE))) {
138 String line;
139 while ((line = reader.readLine()) != null) {
140 String[] parts = line.split(DELIMITER);
141 if (parts.length >= 6) {
142 String name = parts[0];
143 String id = parts[1];
144 String password = parts[2];
145 String email = parts[3];
146 String phoneNumber = parts[4];
147 String address = parts[5];
148 Instructor instructor = new Instructor(name, id, password, email, phoneNumber, address, new
149 ArrayList<>());
150 if (isInstructorIdUnique(id)) {
151 instructors.add(instructor);
152 }
153 }
154 }
155 } catch (FileNotFoundException e) {
156 System.out.println("Instructors file not found. Starting with empty instructor list.");
157 } catch (IOException e) {
158 System.out.println("Error reading instructors file: " + e.getMessage());
159 }
160 }
161 // Save Instructors to file
162 void saveInstructors() {
163 try (BufferedWriter writer = new BufferedWriter(new FileWriter(INSTRUCTORS_FILE))) {
164 for (Instructor instructor : instructors) {
165 String line = String.join("|",
166 instructor.getName(),
167 instructor.getId(),
168 instructor.getPassword(),
169 instructor.getEmail(),
171 instructor.getPhoneNumber(),
172 instructor.getAddress());
173 writer.write(line);
174 writer.newLine();
175 }
176 } catch (IOException e) {
177 System.out.println("Error writing instructors file: " + e.getMessage());
178 }
179 }
180 // Load Administrators from file
181 private void loadAdministrators() {
182 try (BufferedReader reader = new BufferedReader(new FileReader(ADMINISTRATORS_FILE))) {
183 String line;
184 while ((line = reader.readLine()) != null) {
185 String[] parts = line.split(DELIMITER);
186 if (parts.length >= 6) {
187 String name = parts[0];
188 String id = parts[1];
189 String password = parts[2];
190 String email = parts[3];
191 String phoneNumber = parts[4];
192 String address = parts[5];
193 Administrator admin = new Administrator(name, id, password, email, phoneNumber, address);
194 if (isAdminIdUnique(id)) {
195 administrators.add(admin);
196 }
197 }
198 }
199 } catch (FileNotFoundException e) {
200 System.out.println("Administrators file not found. Starting with default admin.");
201 } catch (IOException e) {
202 System.out.println("Error reading administrators file: " + e.getMessage());
203 }
204 }
205 // Save Administrators to file
206 private void saveAdministrators() {
207 try (BufferedWriter writer = new BufferedWriter(new FileWriter(ADMINISTRATORS_FILE))) {
209 for (Administrator admin : administrators) {
210 String line = String.join("|",
211 admin.getName(),
212 admin.getId(),
213 admin.getPassword(),
214 admin.getEmail(),
215 admin.getPhoneNumber(),
216 admin.getAddress());
217 writer.write(line);
218 writer.newLine();
219 }
220 } catch (IOException e) {
221 System.out.println("Error writing administrators file: " + e.getMessage());
222 }
223 }
224 // Load Courses from file
225 private void loadCourses() {
226 try (BufferedReader reader = new BufferedReader(new FileReader(COURSES_FILE))) {
227 String line;
228 while ((line = reader.readLine()) != null) {
229 String[] parts = line.split(DELIMITER);
230 if (parts.length >= 8) {
231 String courseName = parts[0];
232 String courseCode = parts[1];
233 String schedule = parts[2].isEmpty() ? null : parts[2];
234 String description = parts[3].isEmpty() ? null : parts[3];
235 Course.EnrollmentStatusEnum status = Course.EnrollmentStatusEnum.valueOf(parts[4]);
236 Instructor instructor = parts[5].isEmpty() ? null : getInstructorById(parts[5]);
237 int capacity = Integer.parseInt(parts[6]);
238 int creditHours = Integer.parseInt(parts[7]);
239 List<Student> enrolledStudents = new ArrayList<>();
240 if (parts.length > 8 && !parts[8].isEmpty()) {
241 String[] studentIds = parts[8].split(",");
242 for (String id : studentIds) {
243 Student student = getStudentById(id.trim());
244 if (student != null) {
245 enrolledStudents.add(student);
247 }
248 }
249 }
250 Course course = new Course(courseName, courseCode, schedule, description, status, instructor,
251 capacity, new ArrayList<>(), creditHours);
252 course.setEnrolledStudents(enrolledStudents);
253 if (isCourseCodeUnique(courseCode)) {
254 courses.add(course);
255 }
256 }
257 }
258 } catch (FileNotFoundException e) {
259 System.out.println("Courses file not found. Starting with empty course list.");
260 } catch (IOException e) {
261 System.out.println("Error reading courses file: " + e.getMessage());
262 } catch (IllegalArgumentException e) {
263 System.out.println("Error parsing course data: " + e.getMessage());
264 }
265 }
266 // Save Courses to file
267 void saveCourses() {
268 try (BufferedWriter writer = new BufferedWriter(new FileWriter(COURSES_FILE))) {
269 for (Course course : courses) {
270 StringBuilder studentIds = new StringBuilder();
271 for (Student student : course.getEnrolledStudents()) {
272 if (studentIds.length() > 0) {
273 studentIds.append(",");
274 }
275 studentIds.append(student.getId());
276 }
277 String instructorId = course.getInstructor() != null ? course.getInstructor().getId() : "";
278 String schedule = course.getSchedule() != null ? course.getSchedule() : "";
279 String description = course.getDescription() != null ? course.getDescription() : "";
280 String line = String.join("|",
281 course.getCourseName(),
282 course.getCourseCode(),
283 schedule,
285 description,
286 course.getEnrollmentStatus().toString(),
287 instructorId,
288 String.valueOf(course.getCapacity()),
289 String.valueOf(course.getCreditHours()),
290 studentIds.toString());
291 writer.write(line);
292 writer.newLine();
293 }
294 } catch (IOException e) {
295 System.out.println("Error writing courses file: " + e.getMessage());
296 }
297 }
298 // Load Assessments from file
299 private void loadAssessments() {
300 try (BufferedReader reader = new BufferedReader(new FileReader(ASSESSMENTS_FILE))) {
301 String line;
302 while ((line = reader.readLine()) != null) {
303 String[] parts = line.split(DELIMITER);
304 if (parts.length >= 5) {
305 String studentId = parts[0];
306 String courseCode = parts[1];
307 Assessment.ExamType examType = Assessment.ExamType.valueOf(parts[2]);
308 double score = Double.parseDouble(parts[3]);
309 String assessmentName = parts[4];
310 Assessment assessment = new Assessment(studentId, courseCode, examType, score,
311 assessmentName);
312 grades.add(assessment);
313 }
314 }
315 } catch (FileNotFoundException e) {
316 System.out.println("Assessments file not found. Starting with empty assessment list.");
317 } catch (IOException e) {
318 System.out.println("Error reading assessments file: " + e.getMessage());
319 } catch (IllegalArgumentException e) {
320 System.out.println("Error parsing assessment data: " + e.getMessage());
321 }
323 }
324 // Save Assessments to file
325 private void saveAssessments() {
326 try (BufferedWriter writer = new BufferedWriter(new FileWriter(ASSESSMENTS_FILE))) {
327 for (Assessment assessment : grades) {
328 String line = String.join("|",
329 assessment.getStudentId(),
330 assessment.getCourseCode(),
331 assessment.getExamType().toString(),
332 String.valueOf(assessment.getScore()),
333 assessment.getAssessmentName());
334 writer.write(line);
335 writer.newLine();
336 }
337 } catch (IOException e) {
338 System.out.println("Error writing assessments file: " + e.getMessage());
339 }
340 }
341 // Methods for Students
342 public void addStudent(Student student) {
343 if (student == null) {
344 System.out.println("Error: Student cannot be null.");
345 return;
346 }
347 if (isStudentIdUnique(student.getId())) {
348 students.add(student);
349 saveStudents();
350 System.out.printf("Student added: %s with ID: %s%n", student.getName(), student.getId());
351 } else {
352 System.out.println("Error: Student ID " + student.getId() + " already exists.");
353 }
354 }
356 public boolean removeStudent(String studentId) {
357 Iterator<Student> iterator = students.iterator();
358 while (iterator.hasNext()) {
359 Student student = iterator.next();
361 if (student.getId().equals(studentId)) {
362 iterator.remove();
363 saveStudents();
364 System.out.printf("Student %s with ID: %s removed successfully.%n", student.getName(), studentId);
365 return true;
366 }
367 }
368 System.out.println("Student with ID: " + studentId + " not found.");
369 return false;
370 }
372 public Student getStudentById(String studentId) {
373 for (Student student : students) {
374 if (student.getId().equals(studentId)) {
375 return student;
376 }
377 }
378 return null;
379 }
381 public List<Student> getAllStudents() {
382 return students;
383 }
385 // Methods for Instructors
386 public void addInstructor(Instructor instructor) {
387 if (instructor == null) {
388 System.out.println("Error: Instructor cannot be null.");
389 return;
390 }
391 if (isInstructorIdUnique(instructor.getId())) {
392 instructors.add(instructor);
393 saveInstructors();
394 System.out.printf("Instructor added: %s with ID: %s%n", instructor.getName(), instructor.getId());
395 } else {
396 System.out.println("Error: Instructor ID " + instructor.getId() + " already exists.");
397 }
399 }
401 public boolean removeInstructor(String instructorId) {
402 Iterator<Instructor> iterator = instructors.iterator();
403 while (iterator.hasNext()) {
404 Instructor instructor = iterator.next();
405 if (instructor.getId().equals(instructorId)) {
406 for (Course course : courses) {
407 if (course.getInstructor() != null && course.getInstructor().getId().equals(instructorId)) {
408 course.setInstructor(null);
409 }
410 }
411 iterator.remove();
412 saveInstructors();
413 saveCourses();
414 System.out.printf("Instructor %s with ID: %s removed successfully.%n", instructor.getName(),instructorId);
415 return true;
416 }
417 }
418 System.out.println("Instructor with ID: " + instructorId + " not found.");
419 return false;
420 }
422 public Instructor getInstructorById(String instructorId) {
423 for (Instructor instructor : instructors) {
424 if (instructor.getId().equals(instructorId)) {
425 return instructor;
426 }
427 }
428 return null;
429 }
431 public List<Instructor> getAllInstructors() {
432 return instructors;
433 }
435 // Methods for Administrators
437 public void addAdministrator(Administrator admin) {
438 if (admin == null) {
439 System.out.println("Error: Administrator cannot be null.");
440 return;
441 }
442 if (isAdminIdUnique(admin.getId())) {
443 administrators.add(admin);
444 saveAdministrators();
445 System.out.printf("Administrator added: %s with ID: %s%n", admin.getName(), admin.getId());
446 } else {
447 System.out.println("Error: Administrator ID " + admin.getId() + " already exists.");
448 }
449 }
451 public Administrator getAdminById(String adminId) {
452 for (Administrator admin : administrators) {
453 if (admin.getId().equals(adminId)) {
454 return admin;
455 }
456 }
457 return null;
458 }
460 public List<Administrator> getAllAdministrators() {
461 return administrators;
462 }
464 // Methods for Courses
465 public void addCourse(Course course) {
466 if (course == null) {
467 System.out.println("Error: Course cannot be null.");
468 return;
469 }
470 if (isCourseCodeUnique(course.getCourseCode())) {
471 courses.add(course);
472 saveCourses();
474 System.out.printf("Course added: %s (%s) successfully.%n", course.getCourseName(),
475 course.getCourseCode());
476 } else {
477 System.out.println("Error: Course code " + course.getCourseCode() + " already exists.");
478 }
479 }
481 public boolean removeCourse(String courseCode) {
482 Iterator<Course> iterator = courses.iterator();
483 while (iterator.hasNext()) {
484 Course course = iterator.next();
485 if (course.getCourseCode().equals(courseCode)) {
486 for (Student student : course.getEnrolledStudents()) {
487 student.getEnrolledCoursesList().remove(course);
488 }
489 iterator.remove();
490 saveCourses();
491 saveStudents();
492 System.out.printf("Course %s (%s) removed successfully.%n", course.getCourseName(), courseCode);
493 return true;
494 }
495 }
496 System.out.println("Course with code: " + courseCode + " not found.");
497 return false;
498 }
500 public Course getCourseByCode(String courseCode) {
501 for (Course course : courses) {
502 if (course.getCourseCode().equals(courseCode)) {
503 return course;
504 }
505 }
506 return null;
507 }
509 public List<Course> getAllCourses() {
510 return courses;
512 }
513 // =======================Methods for Assessments=======================
514 public void addAssessment(Assessment assessment) {
515 if (assessment == null) {
516 System.out.println("Error: Assessment cannot be null.");
517 return;
518 }
519 grades.add(assessment);
520 saveAssessments();
521 System.out.println("Assessment recorded successfully.");
522 }
524 public void updateAssessment(String studentId, String courseCode, Assessment.ExamType examType, double
525 score) {
526 for (Assessment assessment : grades) {
527 if (assessment.getStudentId().equals(studentId) &&
528 assessment.getCourseCode().equals(courseCode) &&
529 assessment.getExamType() == examType) {
530 assessment.setScore(score);
531 saveAssessments();
532 System.out.println("Assessment updated successfully.");
533 return;
534 }
535 }
536 Assessment newAssessment = new Assessment(studentId, courseCode, examType, score, examType.name());
537 grades.add(newAssessment);
538 saveAssessments();
539 System.out.println("Assessment recorded successfully.");
540 }
542 public List<Assessment> getAssessmentsByStudentAndCourse(String studentId, String courseCode) {
543 List<Assessment> studentAssessments = new ArrayList<>();
544 for (Assessment assessment : grades) {
545 if (assessment.getStudentId().equals(studentId) && assessment.getCourseCode().equals(courseCode)) {
546 studentAssessments.add(assessment);
547 }
548 }
550 return studentAssessments;
551 }
553 public List<Assessment> getAllAssessments() {
554 return grades;
555 }
557 // Validation methods
558 private boolean isStudentIdUnique(String studentId) {
559 return students.stream().noneMatch(student -> student.getId().equals(studentId));
560 }
562 private boolean isInstructorIdUnique(String instructorId) {
563 return instructors.stream().noneMatch(instructor -> instructor.getId().equals(instructorId));
564 }
565 private boolean isAdminIdUnique(String adminId) {
566 return administrators.stream().noneMatch(admin -> admin.getId().equals(adminId));
567 }
569 private boolean isCourseCodeUnique(String courseCode) {
570 return courses.stream().noneMatch(course -> course.getCourseCode().equals(courseCode));
571 }
573 //======================= Utility methods=======================
574 public void assignInstructorToCourse(String courseCode, String instructorId) {
575 Course course = getCourseByCode(courseCode);
576 Instructor instructor = getInstructorById(instructorId);
578 if (course == null) {
579 System.out.println("Error: Course with code " + courseCode + " not found.");
580 return;
581 }
582 if (instructor == null) {
583 System.out.println("Error: Instructor with ID " + instructorId + " not found.");
584 return;
585 }
587 if (course.getInstructor() == null) {
588 course.setInstructor(instructor);
589 saveCourses();
590 System.out.printf("Instructor %s assigned to %s.%n", instructor.getName(), course.getCourseName());
591 } else if (course.getInstructor().equals(instructor)) {
592 System.out.printf("Instructor %s is already assigned to %s.%n", instructor.getName(),
593 course.getCourseName());
594 } else {
595 System.out.println("Course already has a different instructor assigned.");
596 }
597 }
599 public void enrollStudentInCourse(String studentId, String courseCode) {
600 Student student = getStudentById(studentId);
601 Course course = getCourseByCode(courseCode);
603 if (student == null) {
604 System.out.println("Error: Student with ID " + studentId + " not found.");
605 return;
606 }
607 if (course == null) {
608 System.out.println("Error: Course with code " + courseCode + " not found.");
609 return;
610 }
611 student.enroll_In_Course(course);
612 if (course.getEnrolledStudents().contains(student)) {
613 saveStudents();
614 saveCourses();
615 }
616 }
618 public void dropStudentFromCourse(String studentId, String courseCode) {
619 Student student = getStudentById(studentId);
620 Course course = getCourseByCode(courseCode);
622 if (student == null) {
623 System.out.println("Error: Student with ID " + studentId + " not found.");
625 return;
626 }
627 if (course == null) {
628 System.out.println("Error: Course with code " + courseCode + " not found.");
629 return;
630 }
632 student.dropCourse(course);
633 if (!course.getEnrolledStudents().contains(student)) {
634 saveStudents();
635 saveCourses();
636 }
637 }
639 public void closeCourse(String courseCode) {
640 Course course = getCourseByCode(courseCode);
641 if (course == null) {
642 System.out.println("Error: Course with code " + courseCode + " not found.");
643 return;
644 }
646 if (course.getEnrolledStudents().size() >= course.getCapacity()) {
647 System.out.println(course.getCourseName() + " is at full capacity.");
648 course.setEnrollmentStatus(Course.EnrollmentStatusEnum.Closed);
649 } else if (course.getEnrollmentStatus() == Course.EnrollmentStatusEnum.Closed) {
650 System.out.println(course.getCourseName() + " enrollment status is already closed.");
651 } else {
652 System.out.println(course.getCourseName() + " still has available capacity.");
653 course.setEnrollmentStatus(Course.EnrollmentStatusEnum.Closed);
654 }
655 saveCourses();
656 }
657 public void viewEnrollmentStatistics() {
658 int totalEnrolled = 0;
659 boolean openCoursesExist = false;
661 System.out.println("\n---------Enrollment Statistics---------");
663 for (Course course : courses) {
664 int count = course.getEnrolledStudents() != null ? course.getEnrolledStudents().size() : 0;
665 totalEnrolled += count;
666 System.out.printf("Course: %s (%s) - Enrolled: %d%n", course.getCourseName(), course.getCourseCode(),
667 count);
668 if (course.getEnrollmentStatus() == Course.EnrollmentStatusEnum.Open) {
669 openCoursesExist = true;
670 }
671 }
672 System.out.println("Total enrolled students across all courses: " + totalEnrolled);
673 System.out.println("Open courses available: " + (openCoursesExist ? "Yes" : "No"));
674 }
676 public void generateReports() {
677 System.out.println("\n---------Enrollment Report---------");
679 Course mostPopular = null;
680 int maxEnrolled = 0;
682 for (Course course : courses) {
683 int enrolled = course.getEnrolledStudents() != null ? course.getEnrolledStudents().size() : 0;
684 if (enrolled > maxEnrolled) {
685 mostPopular = course;
686 maxEnrolled = enrolled;
687 }
688 }
689 if (mostPopular != null) {
690 System.out.printf("Most popular course: %s (%s) - Enrolled: %d.%n", mostPopular.getCourseName(),
691 mostPopular.getCourseCode(), maxEnrolled);
692 } else {
693 System.out.println("No enrollments found.");
694 }
695 }