From 108c168ba331c15cb0370323d6328920280447e0 Mon Sep 17 00:00:00 2001 From: AshongCyril Date: Fri, 8 Aug 2025 01:29:40 +0000 Subject: [PATCH 1/2] Added the filterSuppliers method which uses Supplier.filterSuppliers to filter by location and/or delivery time, using safeInt --- .../src/Supplier.java | 99 +++++-------------- 1 file changed, 27 insertions(+), 72 deletions(-) diff --git a/Pharmacy Inventory Management/src/Supplier.java b/Pharmacy Inventory Management/src/Supplier.java index ff759cf..d95e7c9 100644 --- a/Pharmacy Inventory Management/src/Supplier.java +++ b/Pharmacy Inventory Management/src/Supplier.java @@ -1,10 +1,9 @@ import java.io.Serializable; import java.util.*; +import java.util.stream.Collectors; public class Supplier implements Serializable { - public String name; - public String location; - public String id; + public String name, location, id; public int deliveryTimeDays; public Supplier(String name, String location, String id, int deliveryTimeDays) { @@ -14,80 +13,36 @@ public Supplier(String name, String location, String id, int deliveryTimeDays) { this.deliveryTimeDays = deliveryTimeDays; } - @Override - public String toString() { - return String.format("Supplier{name='%s', location='%s', id='%s', deliveryTimeDays=%d}", - name, location, id, deliveryTimeDays); - } - - // Nested static class to manage drugs and their suppliers - public static class DrugSupplierManager { - private Map> drugSupplierMap = new HashMap<>(); - - // Add a supplier to a drug - public void addSupplierToDrug(String drugName, Supplier supplier) { - drugSupplierMap - .computeIfAbsent(drugName, k -> new ArrayList<>()) - .add(supplier); - } - - // Get all suppliers for a specific drug - public List getSuppliersForDrug(String drugName) { - return drugSupplierMap.getOrDefault(drugName, new ArrayList<>()); - } - - // Filter suppliers by location - public List filterSuppliersByLocation(String location) { - Set result = new HashSet<>(); - for (List suppliers : drugSupplierMap.values()) { - for (Supplier s : suppliers) { - if (s.location.equalsIgnoreCase(location)) { - result.add(s); - } - } - } - return new ArrayList<>(result); - } - - // Filter suppliers by delivery time (<= maxDays) - public List filterSuppliersByDeliveryTime(int maxDays) { - Set result = new HashSet<>(); - for (List suppliers : drugSupplierMap.values()) { - for (Supplier s : suppliers) { - if (s.deliveryTimeDays <= maxDays) { - result.add(s); - } - } - } - return new ArrayList<>(result); + // Filter suppliers by location (case-insensitive partial match) + public static List filterByLocation(List suppliers, String location) { + if (location == null || location.trim().isEmpty()) { + return new ArrayList<>(suppliers); } + String searchLocation = location.toLowerCase(); + return suppliers.stream() + .filter(s -> s.location != null && s.location.toLowerCase().contains(searchLocation)) + .collect(Collectors.toList()); } - // Main method for testing - public static void main(String[] args) { - DrugSupplierManager manager = new DrugSupplierManager(); - - Supplier s1 = new Supplier("PharmaPlus", "Accra", "S001", 2); - Supplier s2 = new Supplier("MediLife", "Kumasi", "S002", 5); - Supplier s3 = new Supplier("HealthDirect", "Accra", "S003", 3); - - manager.addSupplierToDrug("Paracetamol", s1); - manager.addSupplierToDrug("Paracetamol", s2); - manager.addSupplierToDrug("Ibuprofen", s3); - - System.out.println("Suppliers for Paracetamol:"); - for (Supplier s : manager.getSuppliersForDrug("Paracetamol")) { - System.out.println(s); + // Filter suppliers by maximum delivery time in days + public static List filterByDeliveryTime(List suppliers, int maxDeliveryDays) { + if (maxDeliveryDays < 0) { + return new ArrayList<>(); } + return suppliers.stream() + .filter(s -> s.deliveryTimeDays <= maxDeliveryDays) + .collect(Collectors.toList()); + } - System.out.println("\nSuppliers in Accra:"); - for (Supplier s : manager.filterSuppliersByLocation("Accra")) { - System.out.println(s); + // Combined filter for both location and delivery time + public static List filterSuppliers(List suppliers, String location, int maxDeliveryDays) { + List result = suppliers; + if (location != null && !location.trim().isEmpty()) { + result = filterByLocation(result, location); } - - System.out.println("\nSuppliers with delivery time <= 3 days:"); - for (Supplier s : manager.filterSuppliersByDeliveryTime(3)) { - System.out.println(s); + if (maxDeliveryDays >= 0) { + result = filterByDeliveryTime(result, maxDeliveryDays); } + return result; } -} +} \ No newline at end of file From 56db8da0875b125e4cacbf314e9917dd5f5c133d Mon Sep 17 00:00:00 2001 From: AshongCyril Date: Fri, 8 Aug 2025 01:30:45 +0000 Subject: [PATCH 2/2] Add supplier filtering and management to PharmacySystem - Integrated Supplier class with filter methods for location and delivery time - Added supplierMap (HashMap) to store Supplier objects - Modified addDrug to prompt for new supplier details and validate IDs - Added menu options for adding, listing, and filtering suppliers - Updated saveData and loadData for supplier persistence in suppliers.dat - Simplified filterSuppliers method with basic loops for student-like code - Ensured drug-supplier linking via adjacency list (Drug.suppliers) - Maintained no external libraries, using in-memory HashMap and ArrayList --- .../src/PharmacySystem.java | 244 +++++++++++++----- 1 file changed, 177 insertions(+), 67 deletions(-) diff --git a/Pharmacy Inventory Management/src/PharmacySystem.java b/Pharmacy Inventory Management/src/PharmacySystem.java index 8c6b266..f1449e8 100644 --- a/Pharmacy Inventory Management/src/PharmacySystem.java +++ b/Pharmacy Inventory Management/src/PharmacySystem.java @@ -1,24 +1,28 @@ import java.io.*; import java.util.*; +import java.util.stream.Collectors; -// Enhanced system with purchase/sales tracking and file-based persistence public class PharmacySystem { static HashMap drugMap = new HashMap<>(); + static HashMap supplierMap = new HashMap<>(); static Queue purchaseHistory = new LinkedList<>(); static Stack salesLog = new Stack<>(); + static final String DRUG_FILE = "drugs.dat"; + static final String SUPPLIER_FILE = "suppliers.dat"; static final String PURCHASE_FILE = "purchases.dat"; static final String SALES_FILE = "sales.dat"; public static void main(String[] args) { - loadData(); // Load saved data + loadData(); Scanner sc = new Scanner(System.in); while (true) { - System.out.println("\n-- Atinka Meds Pharmacy System --"); - System.out.println( - "1. Add Drug\n2. List Drugs\n3. Record Purchase\n4. Record Sale\n5. Search Drug\n6. Sort Drugs\n7. View Purchases\n8. View Sales\n9. Save & Exit"); - int choice = safeIntInput(sc, "Choose an option: "); + System.out.println("\n--- Atinka Meds Pharmacy System ---"); + System.out.println("1. Add Drug\n2. List Drugs\n3. Record Purchase\n4. Record Sale"); + System.out.println("5. Search Drug\n6. Sort Drugs\n7. View Purchases\n8. View Sales"); + System.out.println("9. Add Supplier\n10. List Suppliers\n11. Filter Suppliers\n12. Exit"); + int choice = safeInt(sc, "Choice: "); switch (choice) { case 1 -> addDrug(sc); @@ -29,8 +33,12 @@ public static void main(String[] args) { case 6 -> sortDrugs(sc); case 7 -> viewPurchases(); case 8 -> viewSales(); - case 9 -> { + case 9 -> addSupplier(sc); + case 10 -> listSuppliers(); + case 11 -> filterSuppliers(sc); + case 12 -> { saveData(); + System.out.println("Goodbye."); return; } default -> System.out.println("Invalid option."); @@ -38,60 +46,80 @@ public static void main(String[] args) { } } - // Validate integer input - static int safeIntInput(Scanner sc, String prompt) { + static int safeInt(Scanner sc, String prompt) { while (true) { System.out.print(prompt); if (sc.hasNextInt()) { - int value = sc.nextInt(); - sc.nextLine(); // consume newline - return value; + int n = sc.nextInt(); + sc.nextLine(); + return n; } else { - System.out.println("Invalid input. Please enter a number."); - sc.nextLine(); // clear input + System.out.println("Invalid number."); + sc.nextLine(); } } } - // Validate double input - static double safeDoubleInput(Scanner sc, String prompt) { + static double safeDouble(Scanner sc, String prompt) { while (true) { System.out.print(prompt); if (sc.hasNextDouble()) { - double value = sc.nextDouble(); + double d = sc.nextDouble(); sc.nextLine(); - return value; + return d; } else { - System.out.println("Invalid input. Please enter a decimal number."); + System.out.println("Invalid decimal."); sc.nextLine(); } } } - // Add a new drug to inventory static void addDrug(Scanner sc) { System.out.print("Name: "); String name = sc.nextLine(); System.out.print("Code: "); String code = sc.nextLine(); + if (drugMap.containsKey(code)) { + System.out.println("Drug code already exists."); + return; + } System.out.print("Expiration Date: "); String exp = sc.nextLine(); - double price = safeDoubleInput(sc, "Price: "); - int stock = safeIntInput(sc, "Stock: "); - System.out.print("Suppliers (comma separated): "); - List suppliers = Arrays.asList(sc.nextLine().split(",")); - drugMap.put(code, new Drug(name, code, exp, price, stock, suppliers)); + double price = safeDouble(sc, "Price: "); + int stock = safeInt(sc, "Stock: "); + System.out.print("Suppliers (comma-separated IDs, or press Enter to skip): "); + String supplierInput = sc.nextLine(); + List suppliers = supplierInput.isEmpty() ? new ArrayList<>() : Arrays.asList(supplierInput.split(",")); + + // Prompt for supplier details if new supplier IDs are provided + for (String sid : suppliers) { + String supplierId = sid.trim(); + if (!supplierId.isEmpty() && !supplierMap.containsKey(supplierId)) { + System.out.println("New supplier detected: " + supplierId); + System.out.print("Supplier Name: "); + String supplierName = sc.nextLine(); + System.out.print("Supplier Location: "); + String location = sc.nextLine(); + int deliveryTime = safeInt(sc, "Delivery Time (days): "); + supplierMap.put(supplierId, new Supplier(supplierName, location, supplierId, deliveryTime)); + } + } + + Drug d = new Drug(name, code, exp, price, stock, suppliers); + drugMap.put(code, d); System.out.println("Drug added."); } - // Display all drugs static void listDrugs() { + if (drugMap.isEmpty()) { + System.out.println("No drugs found."); + return; + } for (Drug d : drugMap.values()) { - System.out.println(d.code + " | " + d.name + " | Price: " + d.price + " | Stock: " + d.stock); + System.out.printf("%s | %s | ₵%.2f | Stock: %d\n", d.code, d.name, d.price, d.stock); } } - // Record a new purchase (incoming stock) static void recordPurchase(Scanner sc) { System.out.print("Drug Code: "); String code = sc.nextLine(); @@ -100,17 +128,18 @@ static void recordPurchase(Scanner sc) { System.out.println("Drug not found."); return; } - int qty = safeIntInput(sc, "Quantity: "); + int qty = safeInt(sc, "Quantity: "); System.out.print("Buyer ID: "); String buyer = sc.nextLine(); String time = new Date().toString(); double total = d.price * qty; d.stock += qty; - purchaseHistory.add(new Transaction(code, qty, time, buyer, total)); + + Transaction t = new Transaction(code, qty, time, buyer, total); + purchaseHistory.add(t); System.out.println("Purchase recorded."); } - // Record a sale (outgoing stock) static void recordSale(Scanner sc) { System.out.print("Drug Code: "); String code = sc.nextLine(); @@ -119,9 +148,9 @@ static void recordSale(Scanner sc) { System.out.println("Drug not found."); return; } - int qty = safeIntInput(sc, "Quantity: "); + int qty = safeInt(sc, "Quantity: "); if (qty > d.stock) { - System.out.println("Insufficient stock."); + System.out.println("Not enough stock."); return; } System.out.print("Buyer ID: "); @@ -129,75 +158,156 @@ static void recordSale(Scanner sc) { String time = new Date().toString(); double total = d.price * qty; d.stock -= qty; - salesLog.push(new Transaction(code, qty, time, buyer, total)); + + Transaction t = new Transaction(code, qty, time, buyer, total); + salesLog.push(t); System.out.println("Sale recorded."); } - // Search for a drug by name or code static void searchDrug(Scanner sc) { - System.out.print("Enter drug name/code: "); - String query = sc.nextLine().toLowerCase(); + System.out.print("Search by name/code: "); + String q = sc.nextLine().toLowerCase(); + boolean found = false; for (Drug d : drugMap.values()) { - if (d.name.toLowerCase().contains(query) || d.code.toLowerCase().contains(query)) { - System.out.println(d.code + " | " + d.name + " | Price: " + d.price + " | Stock: " + d.stock); + if (d.name.toLowerCase().contains(q) || d.code.toLowerCase().contains(q)) { + System.out.printf("%s | %s | ₵%.2f | Stock: %d\n", d.code, d.name, d.price, d.stock); + found = true; } } + if (!found) { + System.out.println("No drugs found."); + } } - // Sort and display drugs by name or price static void sortDrugs(Scanner sc) { List list = new ArrayList<>(drugMap.values()); - System.out.println("Sort by: 1) Name 2) Price"); - int opt = safeIntInput(sc, "Choice: "); - if (opt == 1) { - DrugSearchAndSort.insertionSortByName(list); - } else { - DrugSearchAndSort.insertionSortByPrice(list); + if (list.isEmpty()) { + System.out.println("No drugs to sort."); + return; } + System.out.println("Sort by: 1) Name 2) Price"); + int opt = safeInt(sc, "Option: "); + if (opt == 1) insertionSortByName(list); + else insertionSortByPrice(list); + for (Drug d : list) { - System.out.println(d.code + " | " + d.name + " | Price: " + d.price); + System.out.printf("%s | %s | ₵%.2f\n", d.code, d.name, d.price); + } + } + + static void insertionSortByName(List list) { + for (int i = 1; i < list.size(); i++) { + Drug key = list.get(i); + int j = i - 1; + while (j >= 0 && list.get(j).name.compareToIgnoreCase(key.name) > 0) { + list.set(j + 1, list.get(j)); + j--; + } + list.set(j + 1, key); + } + } + + static void insertionSortByPrice(List list) { + for (int i = 1; i < list.size(); i++) { + Drug key = list.get(i); + int j = i - 1; + while (j >= 0 && list.get(j).price > key.price) { + list.set(j + 1, list.get(j)); + j--; + } + list.set(j + 1, key); } } - // View all recorded purchases static void viewPurchases() { + if (purchaseHistory.isEmpty()) { + System.out.println("No purchases recorded."); + return; + } for (Transaction t : purchaseHistory) { - System.out.println(t.timestamp + " | " + t.drugCode + " | Qty: " + t.quantity + " | Buyer: " + t.buyerId); + System.out.printf("%s | %s | Qty: %d | ₵%.2f | Buyer: %s\n", + t.timestamp, t.drugCode, t.quantity, t.totalCost, t.buyerId); } } - // View all sales records static void viewSales() { + if (salesLog.isEmpty()) { + System.out.println("No sales recorded."); + return; + } for (Transaction t : salesLog) { - System.out.println(t.timestamp + " | " + t.drugCode + " | Qty: " + t.quantity + " | Buyer: " + t.buyerId); + System.out.printf("%s | %s | Qty: %d | ₵%.2f | Buyer: %s\n", + t.timestamp, t.drugCode, t.quantity, t.totalCost, t.buyerId); + } + } + + static void addSupplier(Scanner sc) { + System.out.print("Supplier ID: "); + String id = sc.nextLine(); + if (supplierMap.containsKey(id)) { + System.out.println("Supplier ID already exists."); + return; + } + System.out.print("Name: "); + String name = sc.nextLine(); + System.out.print("Location: "); + String location = sc.nextLine(); + int deliveryTime = safeInt(sc, "Delivery Time (days): "); + supplierMap.put(id, new Supplier(name, location, id, deliveryTime)); + System.out.println("Supplier added."); + } + + static void listSuppliers() { + if (supplierMap.isEmpty()) { + System.out.println("No suppliers found."); + return; + } + for (Supplier s : supplierMap.values()) { + System.out.printf("%s | %s | %s | Delivery: %d days\n", s.id, s.name, s.location, s.deliveryTimeDays); + } + } + + static void filterSuppliers(Scanner sc) { + System.out.print("Enter location to search (or press Enter to skip): "); + String location = sc.nextLine(); + int maxDeliveryDays = safeInt(sc, "Enter max delivery time (days, or -1 to skip): "); + List filtered = Supplier.filterSuppliers(new ArrayList<>(supplierMap.values()), location, maxDeliveryDays); + if (filtered.isEmpty()) { + System.out.println("No suppliers match the criteria."); + } else { + for (Supplier s : filtered) { + System.out.printf("%s | %s | %s | Delivery: %d days\n", s.id, s.name, s.location, s.deliveryTimeDays); + } } } - // Save all program data to files static void saveData() { - try (ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream(DRUG_FILE)); - ObjectOutputStream o2 = new ObjectOutputStream(new FileOutputStream(PURCHASE_FILE)); - ObjectOutputStream o3 = new ObjectOutputStream(new FileOutputStream(SALES_FILE))) { - o1.writeObject(drugMap); - o2.writeObject(purchaseHistory); - o3.writeObject(salesLog); + try (ObjectOutputStream out1 = new ObjectOutputStream(new FileOutputStream(DRUG_FILE)); + ObjectOutputStream out2 = new ObjectOutputStream(new FileOutputStream(PURCHASE_FILE)); + ObjectOutputStream out3 = new ObjectOutputStream(new FileOutputStream(SALES_FILE)); + ObjectOutputStream out4 = new ObjectOutputStream(new FileOutputStream(SUPPLIER_FILE))) { + out1.writeObject(drugMap); + out2.writeObject(purchaseHistory); + out3.writeObject(salesLog); + out4.writeObject(supplierMap); System.out.println("Data saved."); } catch (IOException e) { System.out.println("Error saving data."); } } - // Load saved data from disk into memory static void loadData() { - try (ObjectInputStream o1 = new ObjectInputStream(new FileInputStream(DRUG_FILE)); - ObjectInputStream o2 = new ObjectInputStream(new FileInputStream(PURCHASE_FILE)); - ObjectInputStream o3 = new ObjectInputStream(new FileInputStream(SALES_FILE))) { - drugMap = (HashMap) o1.readObject(); - purchaseHistory = (Queue) o2.readObject(); - salesLog = (Stack) o3.readObject(); + try (ObjectInputStream in1 = new ObjectInputStream(new FileInputStream(DRUG_FILE)); + ObjectInputStream in2 = new ObjectInputStream(new FileInputStream(PURCHASE_FILE)); + ObjectInputStream in3 = new ObjectInputStream(new FileInputStream(SALES_FILE)); + ObjectInputStream in4 = new ObjectInputStream(new FileInputStream(SUPPLIER_FILE))) { + drugMap = (HashMap) in1.readObject(); + purchaseHistory = (Queue) in2.readObject(); + salesLog = (Stack) in3.readObject(); + supplierMap = (HashMap) in4.readObject(); System.out.println("Data loaded."); } catch (Exception e) { - System.out.println("No previous data found. Starting fresh."); + System.out.println("Starting with empty system..."); } } -} +} \ No newline at end of file