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

utility class· schoolcourseenrolmentsystem

Helpers.java

Helpers is a static utility class. It owns the single Scanner, the generic login, the validators, the three menus and the console flows that collect input before calling the entity classes.

public class Helpers
Type
All static members
Scanner
One shared Scanner on System.in
Generic login
<T extends User<T>> T login(...)
Validators
Predicate<String>-friendly booleans

Responsibilities#

  • Safe integer input that never crashes on bad text
  • Validate names, passwords, emails, phone numbers and addresses
  • One login flow for all three roles, with three password attempts
  • Print the role menus
  • Run the multi-step console flows for each menu option
  • Generate random 10-digit IDs

Fields & enums#

TypeNameModifiersLine
Scannerinputpublic static finalL7

2 methods

Login#

  • <T extends User<T>> T login(List<T> usersList, T tempUser)staticL12

    Ask for an ID, warn if it is unknown, then hand over to the password check.

    • Works for any User subclass through generics
  • <T extends User<T>> T validatePasswordWithRetries(List<T> usersList, T tempUser, String tempID)staticL38

    Up to three password attempts, calling the subclass's own login.

    • After three failures: “Too many failed attempts. Returning to main menu.”

5 methods

Validation#

Each returns true or false so callers can loop until input is valid.

  • boolean ValidatePassword(String password)staticL62

    Longer than 8 characters.

  • boolean ValidateEmail(String email)staticL75

    Contains both “@” and “.”.

  • boolean ValidatePhoneNumber(String phoneNumber)staticL87

    Exactly 10 characters.

  • boolean ValidateAddress(String address)staticL99

    Longer than 3 characters.

  • Boolean ValidateName(String name)staticL112

    Longer than 3 characters.

6 methods

Input & prompts#

  • int getSafeIntInput(String prompt)staticL148

    Prompt until an integer is typed; bad input is cleared and asked again.

  • User.Role checkValidityOfRole()staticL123

    Loop until 1, 2 or 3 is chosen and return STUDENT, INSTRUCTOR or ADMIN.

  • User.Role updateRolePrompt(User.Role currentRole)staticL167

    Ask whether to change the role; keep the current one on “No”.

  • String updateFieldWithPrompt(String fieldName, String currentValue, Predicate<String> validator)staticL181

    Ask “Do you want to change your <field>?” and validate the new value with a Predicate.

    • Replaces separate updateEmail/updatePassword/… methods
  • String createUserWithPrompt(String fieldName, Predicate<String> validator)staticL200

    Ask for a required field until the Predicate accepts it.

  • String GenerateRandomID()staticL213

    Build a random 10-digit ID from “0123456789”.

3 methods

Menus#

  • void showStudentMenu()staticL230

    Print the 8-option student menu.

  • void showInstructorMenu()staticL243

    Print the 5-option instructor menu.

  • void showAdminMenu()staticL253

    Print the 14-option administrator menu.

3 methods

Student flows#

  • void enroll_In_Course_Student(List<Course> listOfCourses, Student student)staticL316

    List open, non-full courses the student is not in, then enrol in the chosen one.

  • void dropCourse(List<Course> listOfCourses, Student student)staticL356

    Ask for a course code (case-insensitive) and call Student.dropCourse.

  • void updateStudentProfile(Student specificStudent)staticL382

    Walk through password, email, phone and address updates.

2 methods

Instructor flows#

  • void updateCourseInfo(Instructor instructor, List<Course> listOfCourses)staticL276

    Ask for a course code, schedule and description, then call Instructor.updateCourseInfo.

  • void updateInstructorProfile(Instructor instructor)staticL295

    Walk through password, email, phone and address updates.

9 methods

Admin flows#

  • void addStudent(Administrator administrator, List<Student> listOfStudents)staticL402

    Create a student: validated name, unique random ID, validated contact details, credit limit.

  • void removeStudent(Administrator administrator, List<Student> listOfStudents)staticL452

    Ask for an ID and call Administrator.removeStudent.

  • void addInstructor(Administrator administrator, List<Instructor> listOfInstructors)staticL478

    Create an instructor the same way as a student, without a credit limit.

  • void removeInstructor(Administrator administrator, List<Instructor> listOfInstructors)staticL466

    Ask for an ID and call Administrator.removeInstructor.

  • void addCourse(Administrator administrator, List<Course> listOfCourses, List<Instructor> listOfInstructors)staticL521

    Create a course: name, code, capacity, credit hours, optional instructor, Open or Closed.

  • void adminUpdateStudentProfile(Administrator administrator, List<Student> listOfStudents)staticL587

    Find a student by name and ID, then update fields, role and credit limit.

  • void adminUpdateInstructorProfile(Administrator administrator, List<Instructor> listOfInstructors)staticL649

    Find an instructor by name and ID, then update fields and role.

  • void assignInstructor(Administrator administrator, List<Course> listOfCourses, List<Instructor> listOfInstructors)staticL698

    List courses, pick one by number, then assign an instructor by ID.

  • void closeCourse(Administrator administrator, List<Course> listOfCourses)staticL741

    Find a course by name and code, then call Administrator.closeCourse.

2 methods

Reports#

Not called from main(), which uses the dataManager versions instead.

  • void viewEnrollmentStatistics(List<Course> listOfCourses)staticL768

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

  • void generateReports(List<Course> listOfCourses)staticL785

    Print the course with the most enrolled students.

Known issues#

Source

Helpers.java806 lines · from the project report
1package schoolcourseenrolmentsystem;
2
3import java.util.*;
4import java.util.function.Predicate;
5
6public class Helpers {
7 public static final Scanner input = new Scanner(System.in);
8
9 /// <T extends User<T>> This method works with any User (Admin, Instructor,
10 /// Student). T inherits from User<T>.
11 /// The single T will return a single object of type T.
12 public static <T extends User<T>> T login(List<T> usersList, T tempUser) {
13 T loggedInUser = null;
14 try {
15 System.out.print("\nPlease enter your ID: ");
16 String id = input.next();
17 input.nextLine(); // Buffer
19 // Check if the ID exists
20 boolean idExists = false;
21 for (T user : usersList) {
22 if (user.getId().equals(id)) {
23 idExists = true;
24 break;
25 }
26 }
27 if (!idExists) {
28 System.out.println("No user found with the entered ID.");
29 }
30 loggedInUser = validatePasswordWithRetries(usersList, tempUser, id);
31 return loggedInUser;
32 } catch (Exception e) {
34 return loggedInUser;
35 }
36 }
38 public static <T extends User<T>> T validatePasswordWithRetries(List<T> usersList, T tempUser, String tempID) {
39 T loggedInUser = null;
40 int attempts = 0;
41 final int maxAttempts = 3;
43 while (attempts < maxAttempts) {
44 System.out.print("\nPlease enter your password: ");
45 String password = input.nextLine();
47 loggedInUser = tempUser.login(usersList, tempID, password);
49 if (loggedInUser != null) {
50 return loggedInUser;
51 } else {
52 attempts++;
53 if (attempts < maxAttempts) {
54 System.out.println("Incorrect password. Try again (" + (maxAttempts - attempts) + " attempts left).");
55 }
56 }
57 }
58 System.out.println("Too many failed attempts. Returning to main menu.");
59 return null;
60 }
62 public static boolean ValidatePassword(String password) {
63 boolean isValid = false;
64 try {
65 if (password != null && password != "" && password.length() > 8) {
66 isValid = true;
67 }
68 } catch (Exception e) {
69 System.out.println(e.getMessage());
70 }
72 return isValid;
73 }
75 public static boolean ValidateEmail(String email) {
76 boolean isValid = false;
77 try {
78 if (email != null && email != "" && email.contains("@") && email.contains(".")) {
79 isValid = true;
80 }
81 } catch (Exception e) {
82 System.out.println(e.getMessage());
83 }
84 return isValid;
85 }
87 public static boolean ValidatePhoneNumber(String phoneNumber) {
88 boolean isValid = false;
89 try {
90 if (phoneNumber != null && phoneNumber != "" && phoneNumber.length() == 10) {
91 isValid = true;
92 }
93 } catch (Exception e) {
94 System.out.println(e.getMessage());
95 }
96 return isValid;
97 }
99 public static boolean ValidateAddress(String address) {
100 boolean isValid = false;
101 try {
102 if (null != address && address != "" && address.length() > 3) {
103 isValid = true;
104 }
105 } catch (Exception e) {
106 System.out.println(e.getMessage());
107 }
108 return isValid;
110 }
112 public static Boolean ValidateName(String name) {
113 boolean isValid = false;
114 try {
115 if (null != name && name != "" && name.length() > 3) {
116 isValid = true;
117 }
118 } catch (Exception e) {
119 System.out.println(e.getMessage());
120 }
121 return isValid;
122 }
123 public static User.Role checkValidityOfRole() {
124 while (true) {
125 System.out.println("Select a role: \n1. STUDENT \n2. INSTRUCTOR \n3. ADMIN \nOption:");
126 try {
127 int Option = Helpers.getSafeIntInput("\nOption: ");
129 switch (Option) {
130 case 1:
131 return User.Role.STUDENT;
132 case 2:
133 return User.Role.INSTRUCTOR;
134 case 3:
135 return User.Role.ADMIN;
136 default:
137 System.out.println("Invalid selection. Please enter 1, 2, or 3.");
138 }
139 } catch (InputMismatchException e) {
140 System.out.println("Invalid input. Please enter a number.");
141 input.nextLine(); // clear the invalid input
142 }
143 }
144 }
146 /// Method created to avoid InputMismatchException
148 public static int getSafeIntInput(String prompt) {
149 try {
150 int number = -1; // -1 is typically related to false or not true. This is a default number.
151 boolean valid = false;
152 while (!valid) {
153 System.out.print(prompt);
154 //number = Integer.parseInt(input.nextLine());
155 number= input.nextInt();
156 input.nextLine();
157 valid = true;
158 }
159 return number;
160 } catch (Exception e) {
161 System.out.println("Invalid input. Please enter a number.");
162 input.nextLine(); // Clear the invalid input
163 return getSafeIntInput(prompt); // Retry
164 }
165 }
167 public static User.Role updateRolePrompt(User.Role currentRole) {
168 System.out.println("\nDo you want to change the role? \n1.Yes \n2.No");
169 int choice = getSafeIntInput("\nOption: ");
170 input.nextLine();
172 if (choice == 1) {
173 return checkValidityOfRole(); // Assuming you already have this
174 } else {
175 System.out.println("Role remains unchanged.");
176 return currentRole;
177 }
178 }
180 // Predicate <> helps us use premade validators.
181 public static String updateFieldWithPrompt(String fieldName, String currentValue, Predicate<String> validator) {
182 System.out.println("\nDo you want to change your " + fieldName + "? \n1.Yes \n2.No");
183 int choice = Helpers.getSafeIntInput("\nOption: ");
185 if (choice == 1) {
186 System.out.print("\nEnter new " + fieldName + ": ");
187 String newValue = input.nextLine();
188 while (!validator.test(newValue)) {
189 System.out.println("Invalid " + fieldName + ". Please try again.");
190 System.out.print("\nEnter new " + fieldName + ": ");
191 newValue = input.nextLine();
192 }
193 return newValue;
194 } else {
195 System.out.println(fieldName + " remains unchanged.");
196 return currentValue;
197 }
198 }
200 public static String createUserWithPrompt(String fieldName, Predicate<String> validator) {
201 String inputValue;
202 while (true) {
203 System.out.print("\nEnter " + fieldName + ": ");
204 inputValue = input.nextLine();
205 if (!validator.test(inputValue)) { // .test() method is just how you invoke the logic inside the Predicate<>
206 System.out.println("Invalid " + fieldName + ". Please try again.");
207 } else {
208 break;
209 }
210 }
211 return inputValue;
212 }
213 public static String GenerateRandomID() {
214 String numbers = "0123456789";
215 int ID_Length = 10;
216 Random random = new Random();
218 StringBuilder id = new StringBuilder(ID_Length);
220 for (int i = 0; i < ID_Length; i++) {
222 int randomIndex = random.nextInt(numbers.length());
223 char randomChar = numbers.charAt(randomIndex);
224 id.append(randomChar);
225 }
226 return id.toString();
227 }
229 // MENUS
230 public static void showStudentMenu() {
231 System.out.println("");
232 System.out.println("\n---------Student Menu---------");
233 System.out.println("1. View avaliable courses.");
234 System.out.println("2. Enroll in course.");
235 System.out.println("3. View enrolled courses.");
236 System.out.println("4. View credit limit.");
237 System.out.println("5. Drop course.");
238 System.out.println("6. View grades.");
239 System.out.println("7. Update personal information.");
240 System.out.println("8. Logout.");
241 }
243 public static void showInstructorMenu() {
244 System.out.println("");
245 System.out.println("\n---------Instructor Menu---------");
246 System.out.println("1. View enrolled students.");
247 System.out.println("2. Grade assignments.");
248 System.out.println("3. Update course information.");
249 System.out.println("4. Update personal information.");
250 System.out.println("5. Logout.");
251 }
253 public static void showAdminMenu() {
254 System.out.println("");
255 System.out.println("\n---------Administrator Menu---------");
256 System.out.println("1. Add Students.");
257 System.out.println("2. Remove Students.");
258 System.out.println("3. View student list.");
260 System.out.println("4. Add Instructors.");
261 System.out.println("5. Remove Instructors.");
262 System.out.println("6. View instructor list.");
263 System.out.println("7. Add Course.");
264 System.out.println("8. Close Course.");
265 System.out.println("9. Update Student Info.");
266 System.out.println("10. Update Instructor Info.");
267 System.out.println("11. Assign Instructor to Course.");
268 System.out.println("12. View Enrollment Statistics.");
269 System.out.println("13. Generate Reports.");
270 System.out.println("14. Logout.");
271 }
273 // CASES
275 // INSTRUCTOR CASES
276 public static void updateCourseInfo(Instructor instructor, List<Course> listOfCourses) {
277 try {
278 System.out.println("\n---------Update Course Information---------\nEnter the course code of the course you
279 would like to update: ");
280 String courseCode = input.next();
281 input.nextLine(); // Buffer
283 System.out.print("\nEnter new schedule:");
284 String newSchedule = input.nextLine();
286 System.out.print("\nEnter new description: ");
287 String newDescription = input.nextLine();
289 instructor.updateCourseInfo(courseCode, listOfCourses, newSchedule, newDescription);
290 } catch (Exception e) {
291 System.out.println(e.getMessage());
292 }
293 }
295 public static void updateInstructorProfile(Instructor instructor) {
296 try {
298 System.out.println("\n---------Update Personal Profile---------");
299 System.out.println("\nPlease fill out the form to update your profile.");
301 String updatedPassword = Helpers.updateFieldWithPrompt("password", instructor.getPassword(),
302 Helpers::ValidatePassword); // Helpers::ValidatePassword is like an inhanced for-each loop
303 String updateEmail = Helpers.updateFieldWithPrompt("email", instructor.getEmail(), Helpers::ValidateEmail);
304 String updatePhone = Helpers.updateFieldWithPrompt("phone number", instructor.getPhoneNumber(),
305 Helpers::ValidatePhoneNumber);
306 String updateAddress = Helpers.updateFieldWithPrompt("address", instructor.getAddress(),
307 Helpers::ValidateAddress);
308 instructor.updateInstructorPersonalInfo(updatedPassword, updateEmail, updatePhone, updateAddress);
309 System.out.println("Instructor " + instructor.getName() + "'s information updated.");
310 } catch (Exception e) {
311 System.out.println(e.getMessage());
312 }
313 }
315 // STUDENT CASES
316 public static void enroll_In_Course_Student(List<Course> listOfCourses, Student student) {
317 try {
318 System.out.println("\n---------Enroll In Course---------");
320 // Filter available courses
321 List<Course> availableCourses = new ArrayList<>();
322 for (Course course : listOfCourses) {
323 if (!course.isFull() &&
324 course.getEnrollmentStatus() == Course.EnrollmentStatusEnum.Open &&
325 !student.getEnrolledCoursesList().contains(course)) {
326 availableCourses.add(course);
327 }
328 }
330 // Display results
331 if (availableCourses.isEmpty()) {
332 System.out.println("No available courses to enroll in.");
333 } else {
334 System.out.println("Courses available to enroll in:");
336 for (int i = 0; i < availableCourses.size(); i++) {
337 Course course = availableCourses.get(i);
338 System.out.printf("%d. %s (%s)\n", (i + 1), course.getCourseName(), course.getCourseCode());
339 }
340 System.out.print("\nEnter the number of the course you would like to enroll in: ");
341 int selectedCourse = input.nextInt();
342 input.nextLine(); // Consume newline
344 if (selectedCourse >= 1 && selectedCourse <= availableCourses.size()) {
345 Course chosenCourse = availableCourses.get(selectedCourse - 1);
346 student.enroll_In_Course(chosenCourse);
347 } else {
348 System.out.println("Invalid selection: " + selectedCourse);
349 }
350 }
351 } catch (Exception e) {
352 System.out.println(e.getMessage());
353 }
354 }
356 public static void dropCourse(List<Course> listOfCourses, Student student) {
357 try {
358 System.out.println("\n---------Unenroll In Course---------");
359 System.out.print("\nEnter course code of the course you would like to drop: ");
360 String dropCourseCode = input.next();
361 input.nextLine(); // Buffer
363 Course courseCodeToDrop = null;
365 for (Course course : listOfCourses) {
366 if (course.getCourseCode().equalsIgnoreCase(dropCourseCode)) {
367 courseCodeToDrop = course;
368 break;
369 }
370 }
371 if (courseCodeToDrop != null) {
372 student.dropCourse(courseCodeToDrop);
374 } else {
375 System.out.println("No course found with the code" + dropCourseCode + "'.");
376 }
377 } catch (Exception e) {
378 System.out.println(e.getMessage());
379 }
380 }
382 public static void updateStudentProfile(Student specificStudent) {
383 try {
384 System.out.println("\n---------Update Personal Profile---------");
385 System.out.println("\nPlease enter the needed information to update your profile.");
386 String updatedPassword = Helpers.updateFieldWithPrompt("password", specificStudent.getPassword(),
387 Helpers::ValidatePassword); // Helpers::ValidatePassword is like an inhanced for-each loop
388 String updateEmail = Helpers.updateFieldWithPrompt("email", specificStudent.getEmail(),
389 Helpers::ValidateEmail);
390 String updatePhone = Helpers.updateFieldWithPrompt("phone number", specificStudent.getPhoneNumber(),
391 Helpers::ValidatePhoneNumber);
392 String updateAddress = Helpers.updateFieldWithPrompt("address", specificStudent.getAddress(),
393 Helpers::ValidateAddress);
395 specificStudent.updateStudentPersonalInfo(updatedPassword, updateEmail, updatePhone, updateAddress);
396 } catch (Exception e) {
397 System.out.println(e.getMessage());
398 }
399 }
401 // ADMIN CASES
402 public static void addStudent(Administrator administrator, List<Student> listOfStudents) {
403 try {
404 System.out.println("\n---------Create New Student---------");
405 String studentName = "";
406 while (true) {
407 System.out.print("\nEnter student name: ");
408 studentName = input.nextLine();
410 if (!Helpers.ValidateName(studentName)) {
412 System.out.println("Invalid name. Please enter a valid name.");
413 continue;
414 }
415 break;
416 }
417 String studentID;
418 while (true) {
419 studentID = GenerateRandomID();
420 boolean exists = false;
421 for (Student student : listOfStudents) {
422 if (student.getId().equals(studentID)) {
423 exists = true;
424 break;
425 }
426 }
427 if (!exists) {
428 break; // We found a unique ID, exit the loop
429 }
430 }
431 String createPassword = Helpers.createUserWithPrompt("password", Helpers::ValidatePassword);
432 String createEmail = Helpers.createUserWithPrompt("email", Helpers::ValidateEmail);
433 String createPhoneNumber = Helpers.createUserWithPrompt("phone number",
434 Helpers::ValidatePhoneNumber);
435 String createAddress = Helpers.createUserWithPrompt("address", Helpers::ValidateAddress);
437 System.out.print("\nEnter credit limit: ");
438 int creditLimit = input.nextInt();
439 input.nextLine(); // Buffer
441 Student newStudent = new Student(studentName, studentID, createPassword, createEmail,
442 createPhoneNumber, createAddress, creditLimit, new ArrayList<>());
444 administrator.addStudent(newStudent, listOfStudents);
446 } catch (Exception e) {
447 System.out.println(e.getMessage());
448 }
450 }
452 public static void removeStudent(Administrator administrator, List<Student> listOfStudents) {
453 try {
454 System.out.println("\n---------Remove Student---------");
455 System.out.print("\nEnter the ID of the student to remove: ");
456 String targetId = input.next();
457 input.nextLine(); // Buffer
458 administrator.removeStudent(listOfStudents, targetId);
460 } catch (Exception e) {
461 System.out.println(e.getMessage());
462 }
463 System.out.println("Invalid option.");
464 }
466 public static void removeInstructor(Administrator administrator, List<Instructor> listOfInstructors) {
467 try {
468 System.out.println("\n---------Remove Instructor---------");
469 System.out.print("\nEnter the ID of the instructor to remove: ");
470 String targetId = input.next();
471 input.nextLine(); // Buffer
472 administrator.removeInstructor(listOfInstructors, targetId);
473 } catch (Exception e) {
474 System.out.println("Invalid option.");
475 }
476 }
478 public static void addInstructor(Administrator administrator, List<Instructor> listOfInstructors) {
479 try {
480 System.out.println("\n---------Create New Instructor---------");
481 String instructorName = "";
482 while (true) {
483 System.out.print("\nEnter instructor name: ");
484 instructorName = input.nextLine();
485 if (!Helpers.ValidateName(instructorName)) {
486 System.out.println("Invalid name. Please enter a valid name.");
488 continue;
489 }
490 break;
491 }
492 String instructorID;
493 while (true) {
494 instructorID = GenerateRandomID();
495 boolean exists = false;
496 for (Instructor instructor : listOfInstructors) {
497 if (instructor.getId().equals(instructorID)) {
498 exists = true;
499 break;
500 }
501 }
502 if (!exists) {
503 break;
504 }
505 }
506 String createPassword = Helpers.createUserWithPrompt("password", Helpers::ValidatePassword);
507 String createEmail = Helpers.createUserWithPrompt("email", Helpers::ValidateEmail);
508 String createPhoneNumber = Helpers.createUserWithPrompt("phone number",
509 Helpers::ValidatePhoneNumber);
510 String createAddress = Helpers.createUserWithPrompt("address", Helpers::ValidateAddress);
512 Instructor newInstructor = new Instructor(instructorName, instructorID, createPassword, createEmail,
513 createPhoneNumber, createAddress, new ArrayList<>());
515 administrator.addInstructor(newInstructor, listOfInstructors);
516 } catch (Exception e) {
517 System.out.println("Invalid option.");
518 }
519 }
521 public static void addCourse(Administrator administrator, List<Course> listOfCourses,
522 List<Instructor> listOfInstructors) {
523 try {
524 System.out.println("\n---------Create Course---------");
526 System.out.print("\nEnter the course's information that you would like to create.\n\nEnter course name: ");
527 String courseName = input.nextLine();
529 System.out.print("\nEnter course code: ");
530 String courseCode = input.nextLine();
532 System.out.print("\nEnter course capacity: ");
533 int courseCapacity = input.nextInt();
534 input.nextLine(); // Buffer
536 System.out.print("\nEnter course credit hours: ");
537 int courseCreditHours = input.nextInt();
538 input.nextLine(); // Buffer
540 Course newCourse = new Course(courseName, courseCode, null, null, null, null, courseCapacity, null,
541 courseCreditHours);
543 System.out.println("\nWould you like to assign instructor now? \n1. Assign now. \n2. Assign later.");
544 int assignChoice = Helpers.getSafeIntInput("\nOption: ");
546 if (assignChoice == 1) {
547 System.out.print("\nAssign instructor by ID: ");
548 String assignInstructorID = input.nextLine();
550 // Validate instructor list is not empty.
551 if (listOfInstructors.isEmpty()) {
552 System.out.println("\nNo instructors available. Please add an instructor before creating a course.");
553 return; // Stop the method early
554 }
555 Instructor selectedInstructor = null;
556 for (Instructor instructor : listOfInstructors) {
557 if (instructor.getId().equals(assignInstructorID)) {
558 selectedInstructor = instructor;
559 break;
560 }
561 }
562 administrator.assignInstructor(newCourse, selectedInstructor);
564 if (selectedInstructor == null) {
565 System.out.println("\nInstructor with ID " + assignInstructorID + " not found.");
566 }
567 }
568 if (assignChoice == 2) {
569 System.out.println("To be assigned.");
570 }
572 // Assign course status
573 System.out.println("\nEnter course status: \n1. Open \n2.Closed");
574 int courseStatus = Helpers.getSafeIntInput("Option: ");
576 if (courseStatus == 1) {
577 newCourse.setEnrollmentStatus(Course.EnrollmentStatusEnum.Open);
578 } else if (courseStatus == 2) {
579 newCourse.setEnrollmentStatus(Course.EnrollmentStatusEnum.Closed);
580 }
581 administrator.addCourse(listOfCourses, newCourse);
582 } catch (Exception e) {
583 System.out.println(e.getMessage());
584 }
585 }
587 public static void adminUpdateStudentProfile(Administrator administrator, List<Student> listOfStudents) {
588 try {
589 System.out.print("\n---------Update Student Profile---------\nPlease enter the requiered information
590 below.\nStudent's name: ");
591 String name = input.nextLine();
593 System.out.print("\nStudent ID: ");
594 String ID = input.next();
595 input.nextLine(); // Buffer
597 Student studentToUpdate = null;
599 for (Student student : listOfStudents) {
601 if (student.getName().equals(name) && student.getId().equals(ID)) {
602 studentToUpdate = student;
603 break;
604 }
605 }
606 if (studentToUpdate != null) {
607 System.out.println("Update " + studentToUpdate.getName() + " details below: ");
609 String updateName = Helpers.updateFieldWithPrompt("name", studentToUpdate.getName(),
610 Helpers::ValidateName);
611 String updatePassword = Helpers.updateFieldWithPrompt("password", studentToUpdate.getPassword(),
612 Helpers::ValidatePassword);
613 String updateEmail = Helpers.updateFieldWithPrompt("email",
614 studentToUpdate.getEmail(),Helpers::ValidateEmail);
615 String updatePhoneNumber = Helpers.updateFieldWithPrompt("phone number",
616 studentToUpdate.getPhoneNumber(), Helpers::ValidatePhoneNumber);
617 String updateAddress = Helpers.updateFieldWithPrompt("address", studentToUpdate.getAddress(),
618 Helpers::ValidateAddress);
619 User.Role updateRole = Helpers.updateRolePrompt(studentToUpdate.getRole());
621 // Option to update credit limit
622 System.out.printf("\nDo you want to update %s's credit limit?\n1. Yes\n2. No",
623 studentToUpdate.getName());
624 int creditLimitChoice = input.nextInt();
626 if (creditLimitChoice == 1) {
627 System.out.print("\nEnter new credit limit: ");
628 int updatedStudentcreditLimit = input.nextInt();
629 studentToUpdate.setCreditLimit(updatedStudentcreditLimit);
630 } else if (creditLimitChoice == 2) {
631 System.out.println("Credit limit number remains unchanged.");
632 }
633 // Apply updates
634 studentToUpdate.setName(updateName);
635 studentToUpdate.setPassword(updatePassword);
636 studentToUpdate.setEmail(updateEmail);
637 studentToUpdate.setPhoneNumber(updatePhoneNumber);
639 studentToUpdate.setAddress(updateAddress);
640 studentToUpdate.setRole(updateRole);
642 System.out.println("Student " + updateName + "'s profile updated successfully.");
643 }
644 } catch (Exception e) {
645 System.out.println(e.getMessage());
646 }
647 }
649 public static void adminUpdateInstructorProfile(Administrator administrator, List<Instructor> listOfInstructors) {
650 try {
651 System.out.println("\n---------Update Instuctor Profile---------\nPlease enter the requiered information below.");
653 System.out.print("\nEnter instructor name: ");
654 String instructorName = input.nextLine();
656 System.out.print("\nEnter instructor ID: ");
657 String instructorId = input.next();
658 input.nextLine(); // Buffer
660 Instructor instructorToUpdate = null;
662 for (Instructor instructor : listOfInstructors) {
663 if (instructor.getName().equals(instructorName) && instructor.getId().equals(instructorId)) {
664 instructorToUpdate = instructor;
665 break;
666 }
667 }
668 if (instructorToUpdate != null) {
669 System.out.println("Update " + instructorToUpdate.getName() + "'s details below: ");
671 String updateName = Helpers.updateFieldWithPrompt("name", instructorToUpdate.getName(),
672 Helpers::ValidateName);
673 String updatePassword = Helpers.updateFieldWithPrompt("password", instructorToUpdate.getPassword(),
674 Helpers::ValidatePassword);
676 String updateEmail = Helpers.updateFieldWithPrompt("email",
677 instructorToUpdate.getEmail(),Helpers::ValidateEmail);
678 String updatePhoneNumber = Helpers.updateFieldWithPrompt("phone
679 number",instructorToUpdate.getPhoneNumber(), Helpers::ValidatePhoneNumber);
680 String updateAddress = Helpers.updateFieldWithPrompt("address", instructorToUpdate.getAddress(),
681 Helpers::ValidateAddress);
682 User.Role updateRole = Helpers.updateRolePrompt(instructorToUpdate.getRole());
683 // Apply updates
684 instructorToUpdate.setName(updateName);
685 instructorToUpdate.setPassword(updatePassword);
686 instructorToUpdate.setEmail(updateEmail);
687 instructorToUpdate.setPhoneNumber(updatePhoneNumber);
688 instructorToUpdate.setAddress(updateAddress);
689 instructorToUpdate.setRole(updateRole);
691 System.out.println("Instructor " + updateName + "'s profile updated successfully.");
692 }
693 } catch (Exception e) {
694 System.out.println(e.getMessage());
695 }
696 }
698 public static void assignInstructor(Administrator administrator, List<Course> listOfCourses,
699 List<Instructor> listOfInstructors) {
700 try {
701 System.out.println("\n---------Available Courses---------");
703 for (int i = 0; i < listOfCourses.size(); i++) {
704 /// The i+1 is for the indext of which the admin will select. The i is for
705 /// 'this' spesific course.
706 System.out.printf("%d. %s (%s).\n", (i + 1), listOfCourses.get(i).getCourseName(),
707 listOfCourses.get(i).getCourseCode());
708 }
709 System.out.print("\nEnter the number of the course to assign the instructor to: ");
710 int courseIndex = input.nextInt() - 1;
711 input.nextLine(); // Buffer
713 // Basic validation.
714 if (courseIndex < 0 || courseIndex >= listOfCourses.size()) {
715 System.out.println("Invalid course selection.");
716 return;
717 }
718 System.out.print("\nEnter the ID of the instructor to assign: ");
719 String instructorID2 = input.next();
720 input.nextLine(); // Buffer
722 Instructor assignInstructor = null;
724 for (Instructor instructor : listOfInstructors) {
725 if (instructor.getId().equals(instructorID2)) {
726 assignInstructor = instructor;
727 break;
728 }
729 }
730 if (assignInstructor != null) {
731 Course selectedCourse = listOfCourses.get(courseIndex);
732 administrator.assignInstructor(selectedCourse, assignInstructor);
733 } else {
734 System.out.println("Instructor with ID " + instructorID2 + " not found.");
735 }
736 } catch (Exception e) {
737 System.out.println(e.getMessage());
738 }
739 }
741 public static void closeCourse(Administrator administrator, List<Course> listOfCourses) {
742 try {
743 System.out.println("\n---------Close Courses---------\nEnter the details requiered below.\nEnter course name: ");
744 String closeCourseName = input.nextLine();
745 System.out.print("\nEnter course code: ");
746 String closeCourseCode = input.next();
747 input.nextLine(); // Buffer
749 Course courseToClose = null;
751 for (Course course : listOfCourses) {
752 if (course.getCourseName().equals(closeCourseName) &&
753 course.getCourseCode().equals(closeCourseCode)) {
754 courseToClose = course;
755 break;
756 }
757 }
758 if (courseToClose != null) {
759 administrator.closeCourse(courseToClose, listOfCourses);
760 } else {
761 System.out.println("Course not found.");
762 }
763 } catch (Exception e) {
764 System.out.println(e.getMessage());
765 }
766 }
767 // Statistics.
768 public static void viewEnrollmentStatistics(List<Course> listOfCourses) {
769 int totalEnrolled = 0;
770 boolean openCoursesExist = false;
772 System.out.println("\n---------Enrollment Statistics---------");
773 for (Course course : listOfCourses) {
774 int count = course.getEnrolledStudents() != null ? course.getEnrolledStudents().size() : 0;
775 totalEnrolled += count;
776 System.out.printf("Course: %s (%s) - Enrolled: %d", course.getCourseName(), count);
777 if (course.getEnrollmentStatus() == Course.EnrollmentStatusEnum.Open) {
778 openCoursesExist = true;
779 }
780 }
781 System.out.println("Total enrolled students across all courses: " + totalEnrolled);
782 System.out.println("Open courses available: " + (openCoursesExist ? "Yes" : "No"));
783 }
785 public static void generateReports(List<Course> listOfCourses) {
786 System.out.println("\n---------Enrollment Report---------");
788 // Most popular course
789 Course mostPopular = null;
790 int maxEnrolled = 0;
792 for (Course course : listOfCourses) {
793 int enrolled = course.getEnrolledStudents() != null ? course.getEnrolledStudents().size() : 0;
794 if (enrolled > maxEnrolled) {
795 mostPopular = course;
796 maxEnrolled = enrolled;
797 }
798 }
799 if (mostPopular != null) {
800 System.out.printf("\nMost popular course: %s (%s) - Enrolled: %d.", mostPopular.getCourseName(),
801 mostPopular.getCourseCode(), maxEnrolled);
802 } else {
803 System.out.println("No enrollments found.");
804 }
805 }