S 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
Overview
Source 696 lines
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# Type Name Modifiers Line f dataManagerinstanceprivate static L8 f List <Instructor >instructorsprivate L11 f List <Administrator >administratorsprivate L12 f List <Student >studentsprivate L13 f List <Course >coursesprivate L14 f List <Assessment >gradesprivate L15 f String STUDENTS_FILEprivate static final L19 f String INSTRUCTORS_FILEprivate static final L20 f String ADMINISTRATORS_FILEprivate static final L21 f String COURSES_FILEprivate static final L22 f String ASSESSMENTS_FILEprivate static final L23 f String DELIMITERprivate static final L24
12 methods
Load & save# m void loadAllData ()package L44 Load students, instructors, administrators, courses, then assessments.
Students load before courses, so saved course codes cannot be resolved (see Known issues) Write all five lists back to their files.
m void loadStudents ()private L63 Read students.txt. Each line needs at least 7 fields.
Prints every line it loads m void saveStudents ()package L107 Write students.txt, joining enrolled course codes with commas.
m void loadInstructors ()private L136 Read instructors.txt. Each line needs at least 6 fields.
m void saveInstructors ()package L162 Write instructors.txt.
m void loadAdministrators ()private L181 Read administrators.txt. Each line needs at least 6 fields.
m void saveAdministrators ()private L206 Write administrators.txt.
m void loadCourses ()private L225 Read courses.txt, resolving instructor and student IDs. Each line needs at least 8 fields.
m void saveCourses ()package L267 Write courses.txt, joining enrolled student IDs with commas.
m void loadAssessments ()private L299 Read assessments.txt. Each line needs at least 5 fields.
m void saveAssessments ()private L325 Write assessments.txt.
4 methods
Students# m void addStudent (Student student)L342 Add if the ID is unique, then save students.txt.
m boolean removeStudent (String studentId)L356 Remove by ID, then save students.txt.
m Student getStudentById (String studentId)L372 Look up a student, or null.
m List <Student > getAllStudents ()L381 The live student list.
4 methods
Instructors# m void addInstructor (Instructor instructor)L386 Add if the ID is unique, then save instructors.txt.
m boolean removeInstructor (String instructorId)L401 Remove by ID, clear it from any course it taught, then save both files.
m Instructor getInstructorById (String instructorId)L422 Look up an instructor, or null.
m List <Instructor > getAllInstructors ()L431 The live instructor list.
3 methods
Administrators# m void addAdministrator (Administrator admin)L437 Add if the ID is unique, then save administrators.txt.
Called at start-up to register the default admin m Administrator getAdminById (String adminId)L451 Look up an administrator, or null.
m List <Administrator > getAllAdministrators ()L460 The live administrator list.
4 methods
Uniqueness# m boolean isStudentIdUnique (String studentId)private L558 No student already has this ID.
m boolean isInstructorIdUnique (String instructorId)private L562 No instructor already has this ID.
m boolean isAdminIdUnique (String adminId)private L565 No administrator already has this ID.
m boolean isCourseCodeUnique (String courseCode)private L569 No course already has this code.
6 methods
Operations & reports# m void assignInstructorToCourse (String courseCode, String instructorId)L574 Assign by course code and instructor ID, then save courses.
m void enrollStudentInCourse (String studentId, String courseCode)L599 Enrol by IDs and save both files if it worked.
m void dropStudentFromCourse (String studentId, String courseCode)L618 Drop by IDs and save both files if it worked.
m void closeCourse (String courseCode)L639 Close a course by code and save courses.
m void viewEnrollmentStatistics ()L657 Per-course counts, total enrolled, and whether any course is open.
m void generateReports ()L676 Print the most popular course, or “No enrollments found.”
Source S dataManager.java 696 lines · from the project report Copy
1 package schoolcourseenrolmentsystem;6 public class dataManager {8 private static dataManager instance = null ; 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; 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 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" ); 36 public static synchronized dataManager getInstance () { 37 if (instance == null ) { 38 instance = new dataManager (); 43 // Load all data from files 52 // Save all data to files 53 public void saveAllData () { 62 // Load Students from file 63 private void loadStudents () { 64 try (BufferedReader reader = new BufferedReader (new FileReader (STUDENTS_FILE ))) { 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 ]; 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 ()); 85 enrolledCourses.add (course); 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); 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 ()); 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 ("," ); 115 courseCodes.append (course.getCourseCode ()); 117 String line = String .join ("|" , 120 student.getPassword (), 122 student.getPhoneNumber (), 123 student.getAddress (), 124 String .valueOf (student.getCreditLimit ()), 125 courseCodes.toString ()); 129 } catch (IOException e) { 130 System .out.println ("Error writing students file: " + e.getMessage ()); 135 // Load Instructors from file 136 private void loadInstructors () { 137 try (BufferedReader reader = new BufferedReader (new FileReader (INSTRUCTORS_FILE ))) { 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 150 if (isInstructorIdUnique (id)) { 151 instructors.add (instructor); 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 ()); 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 (), 168 instructor.getPassword (), 169 instructor.getEmail (), 171 instructor.getPhoneNumber (), 172 instructor.getAddress ()); 176 } catch (IOException e) { 177 System .out.println ("Error writing instructors file: " + e.getMessage ()); 180 // Load Administrators from file 181 private void loadAdministrators () { 182 try (BufferedReader reader = new BufferedReader (new FileReader (ADMINISTRATORS_FILE ))) { 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); 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 ()); 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 ("|" , 215 admin.getPhoneNumber (), 220 } catch (IOException e) { 221 System .out.println ("Error writing administrators file: " + e.getMessage ()); 224 // Load Courses from file 225 private void loadCourses () { 226 try (BufferedReader reader = new BufferedReader (new FileReader (COURSES_FILE ))) { 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); 250 Course course = new Course (courseName, courseCode, schedule, description, status, instructor, 251 capacity, new ArrayList <>(), creditHours); 252 course.setEnrolledStudents (enrolledStudents); 253 if (isCourseCodeUnique (courseCode)) { 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 ()); 266 // Save Courses to file 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 ("," ); 275 studentIds.append (student.getId ()); 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 (), 286 course.getEnrollmentStatus ().toString (), 288 String .valueOf (course.getCapacity ()), 289 String .valueOf (course.getCreditHours ()), 290 studentIds.toString ()); 294 } catch (IOException e) { 295 System .out.println ("Error writing courses file: " + e.getMessage ()); 298 // Load Assessments from file 299 private void loadAssessments () { 300 try (BufferedReader reader = new BufferedReader (new FileReader (ASSESSMENTS_FILE ))) { 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, 312 grades.add (assessment); 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 ()); 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 ()); 337 } catch (IOException e) { 338 System .out.println ("Error writing assessments file: " + e.getMessage ()); 341 // Methods for Students 342 public void addStudent (Student student) { 343 if (student == null ) { 344 System .out.println ("Error: Student cannot be null." ); 347 if (isStudentIdUnique (student.getId ())) { 348 students.add (student); 350 System .out.printf ("Student added: %s with ID: %s%n" , student.getName (), student.getId ()); 352 System .out.println ("Error: Student ID " + student.getId () + " already exists." ); 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)) { 364 System .out.printf ("Student %s with ID: %s removed successfully.%n" , student.getName (), studentId); 368 System .out.println ("Student with ID: " + studentId + " not found." ); 372 public Student getStudentById (String studentId) { 373 for (Student student : students) { 374 if (student.getId ().equals (studentId)) { 381 public List <Student > getAllStudents () { 385 // Methods for Instructors 386 public void addInstructor (Instructor instructor) { 387 if (instructor == null ) { 388 System .out.println ("Error: Instructor cannot be null." ); 391 if (isInstructorIdUnique (instructor.getId ())) { 392 instructors.add (instructor); 394 System .out.printf ("Instructor added: %s with ID: %s%n" , instructor.getName (), instructor.getId ()); 396 System .out.println ("Error: Instructor ID " + instructor.getId () + " already exists." ); 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 ); 414 System .out.printf ("Instructor %s with ID: %s removed successfully.%n" , instructor.getName (),instructorId); 418 System .out.println ("Instructor with ID: " + instructorId + " not found." ); 422 public Instructor getInstructorById (String instructorId) { 423 for (Instructor instructor : instructors) { 424 if (instructor.getId ().equals (instructorId)) { 431 public List <Instructor > getAllInstructors () { 435 // Methods for Administrators 437 public void addAdministrator (Administrator admin) { 439 System .out.println ("Error: Administrator cannot be null." ); 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 ()); 447 System .out.println ("Error: Administrator ID " + admin.getId () + " already exists." ); 451 public Administrator getAdminById (String adminId) { 452 for (Administrator admin : administrators) { 453 if (admin.getId ().equals (adminId)) { 460 public List <Administrator > getAllAdministrators () { 461 return administrators; 464 // Methods for Courses 465 public void addCourse (Course course) { 466 if (course == null ) { 467 System .out.println ("Error: Course cannot be null." ); 470 if (isCourseCodeUnique (course.getCourseCode ())) { 474 System .out.printf ("Course added: %s (%s) successfully.%n" , course.getCourseName (), 475 course.getCourseCode ()); 477 System .out.println ("Error: Course code " + course.getCourseCode () + " already exists." ); 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); 492 System .out.printf ("Course %s (%s) removed successfully.%n" , course.getCourseName (), courseCode); 496 System .out.println ("Course with code: " + courseCode + " not found." ); 500 public Course getCourseByCode (String courseCode) { 501 for (Course course : courses) { 502 if (course.getCourseCode ().equals (courseCode)) { 509 public List <Course > getAllCourses () { 513 // =======================Methods for Assessments======================= 514 public void addAssessment (Assessment assessment) { 515 if (assessment == null ) { 516 System .out.println ("Error: Assessment cannot be null." ); 519 grades.add (assessment); 521 System .out.println ("Assessment recorded successfully." ); 524 public void updateAssessment (String studentId, String courseCode, Assessment .ExamType examType, double 526 for (Assessment assessment : grades) { 527 if (assessment.getStudentId ().equals (studentId) && 528 assessment.getCourseCode ().equals (courseCode) && 529 assessment.getExamType () == examType) { 530 assessment.setScore (score); 532 System .out.println ("Assessment updated successfully." ); 536 Assessment newAssessment = new Assessment (studentId, courseCode, examType, score, examType.name ()); 537 grades.add (newAssessment); 539 System .out.println ("Assessment recorded successfully." ); 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); 550 return studentAssessments; 553 public List <Assessment > getAllAssessments () { 557 // Validation methods 558 private boolean isStudentIdUnique (String studentId) { 559 return students.stream ().noneMatch (student -> student.getId ().equals (studentId)); 562 private boolean isInstructorIdUnique (String instructorId) { 563 return instructors.stream ().noneMatch (instructor -> instructor.getId ().equals (instructorId)); 565 private boolean isAdminIdUnique (String adminId) { 566 return administrators.stream ().noneMatch (admin -> admin.getId ().equals (adminId)); 569 private boolean isCourseCodeUnique (String courseCode) { 570 return courses.stream ().noneMatch (course -> course.getCourseCode ().equals (courseCode)); 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." ); 582 if (instructor == null ) { 583 System .out.println ("Error: Instructor with ID " + instructorId + " not found." ); 587 if (course.getInstructor () == null ) { 588 course.setInstructor (instructor); 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 ()); 595 System .out.println ("Course already has a different instructor assigned." ); 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." ); 607 if (course == null ) { 608 System .out.println ("Error: Course with code " + courseCode + " not found." ); 611 student.enroll_In_Course (course); 612 if (course.getEnrolledStudents ().contains (student)) { 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." ); 627 if (course == null ) { 628 System .out.println ("Error: Course with code " + courseCode + " not found." ); 632 student.dropCourse (course); 633 if (!course.getEnrolledStudents ().contains (student)) { 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." ); 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." ); 652 System .out.println (course.getCourseName () + " still has available capacity." ); 653 course.setEnrollmentStatus (Course .EnrollmentStatusEnum .Closed ); 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 (), 668 if (course.getEnrollmentStatus () == Course .EnrollmentStatusEnum .Open ) { 669 openCoursesExist = true ; 672 System .out.println ("Total enrolled students across all courses: " + totalEnrolled); 673 System .out.println ("Open courses available: " + (openCoursesExist ? "Yes" : "No" )); 676 public void generateReports () { 677 System .out.println ("\n---------Enrollment Report---------" ); 679 Course mostPopular = null ; 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; 689 if (mostPopular != null ) { 690 System .out.printf ("Most popular course: %s (%s) - Enrolled: %d.%n" , mostPopular.getCourseName (), 691 mostPopular.getCourseCode (), maxEnrolled); 693 System .out.println ("No enrollments found." );