From 28b4d42f9c56824aa73f3b6dbaa1189785981084 Mon Sep 17 00:00:00 2001 From: fdai7921 Date: Wed, 7 Feb 2024 13:27:54 +0100 Subject: [PATCH] Adding deleteCourse method in Course class --- src/main/java/org/example/Course.java | 45 +++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/main/java/org/example/Course.java b/src/main/java/org/example/Course.java index cc95d97..d990da4 100644 --- a/src/main/java/org/example/Course.java +++ b/src/main/java/org/example/Course.java @@ -185,4 +185,49 @@ public class Course { System.out.println("Added Course successfully!"); } + public static void deleteCourse(String filename) { + List courses = readFromFile(filename); + + if (courses.isEmpty()) { + System.out.println("No courses found."); + return; + } + + Scanner scanner = new Scanner(System.in); + + while (true) { + System.out.println("Select the course to delete (or 0 to go back to the menu):"); + + // Display available courses for selection + for (int i = 0; i < courses.size(); i++) { + System.out.println((i + 1) + ". " + courses.get(i).getCourseName()); + } + + int selection = scanner.nextInt(); + + if (selection == 0) { + return; // Return to the menu + } else if (selection < 1 || selection > courses.size()) { + System.out.println("Invalid selection."); + } else { + Course courseToDelete = courses.get(selection - 1); + courses.remove(courseToDelete); + + try (FileWriter writer = new FileWriter(filename)) { + for (Course course : courses) { + writer.write(course.getCourseName() + "\n"); + writer.write(course.getCourseCode() + "\n"); + writer.write(course.getCourseCredit() + "\n"); + // Write any other fields you saved + } + } catch (IOException e) { + System.out.println("An error occurred while deleting the course."); + e.printStackTrace(); + } + + System.out.println("Course deleted successfully."); + return; + } + } + } }