-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHospitalManagementSystem.java
More file actions
executable file
·1034 lines (814 loc) · 36 KB
/
Copy pathHospitalManagementSystem.java
File metadata and controls
executable file
·1034 lines (814 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package hospitalmanagementsystem;
/**
* Main Controller Class for the Hospital Management System.
* This class orchestrates the interaction between all data structures (Hash Table, BST, AVL, Heap, Stack).
* * @author egehanhatipoglu
*/
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Scanner;
public class HospitalManagementSystem {
// CONFIGURATION & CONSTANTS
// The Student ID is used to seed the system's capacity and constraints,
// ensuring the project submission is unique.
private static final int STUDENT_ID = 230316064;
private final int MAX_PATIENT_NUMBER;
private final int MAX_DOCTOR_NUMBER;
// DATA STRUCTURES
// Hash Tables: Used for O(1) instantaneous access to records by ID.
private HashTable<Integer, Patient> patients;
private HashTable<Integer, Doctor> doctors;
private HashTable<Integer, Appointment> appointments;
private HashTable<Integer, Department> departments;
// Trees: Used for searching and hierarchical organization.
private PatientBST patientBST; // Standard Binary Search Tree for name search.
private PatientAVL patientAVL; // AVL Tree for balanced, optimized name search O(log n).
private HospitalTree hospitalTree; // General Tree for hospital department hierarchy.
// queues & Stacks: Used for workflow management.
private ERPriorityQueue erQueue; // Priority Queue (Max-Heap) for Emergency Room Triage.
private UndoStack undoStack; // Stack (LIFO) for undoing administrative actions.
private Scanner input = new Scanner(System.in);
// ID Counters for auto-incrementing unique keys
private int patientIdCounter = 0;
private int doctorIdCounter = 0;
private int appointmentIdCounter = 0;
private int departmentIdCounter = 0;
/**
* Constructor: Initializes the system.
* Sets dynamic capacities based on the Student ID modulo operations.
*/
public HospitalManagementSystem() {
// Dynamic capacity calculation ensures unique runtime behavior
this.MAX_PATIENT_NUMBER = STUDENT_ID % 10 + 3;
this.MAX_DOCTOR_NUMBER = STUDENT_ID % 10 + 8;
// Initialize Hash Tables with custom capacity
this.patients = new HashTable<>(STUDENT_ID);
this.doctors = new HashTable<>(STUDENT_ID);
this.appointments = new HashTable<>(STUDENT_ID);
this.departments = new HashTable<>(STUDENT_ID);
// Initialize other core data structures
this.patientBST = new PatientBST();
this.patientAVL = new PatientAVL();
this.hospitalTree = new HospitalTree("Manisa Celal Bayar University Hospital");
this.erQueue = new ERPriorityQueue();
this.undoStack = new UndoStack();
}
public static void main(String[] args) {
HospitalManagementSystem system = new HospitalManagementSystem();
system.loadInitialSampleData(); // Pre-load data for testing
system.menu(); // Start the main user interface loop
}
/**
* Main Menu Loop.
* Displays options and routes user input to specific handler methods.
*/
void menu() {
while (true) {
System.out.println("");
System.out.println(" HASTANE YÖNETİM SİSTEMİ ");
System.out.println(" ");
System.out.println("1. Yeni Hasta Kaydet");
System.out.println("2. Yeni Doktor Kaydet");
System.out.println("3. Randevu Oluştur");
System.out.println("4. Hastaları Listele (Hash Table)");
System.out.println("5. Doktorları Listele");
System.out.println("6. Randevuları Listele");
System.out.println("7. Doktor Kuyruğunu Göster");
System.out.println("8. Sıradaki Hastayı Muayene Et");
System.out.println("9. Acil Servis İşlemleri");
System.out.println("10. Hasta Tıbbi Geçmişi");
System.out.println("11. Son İşlemi Geri Al (Undo)");
System.out.println("12. İsme Göre Hasta Ara (BST)");
System.out.println("13. Hastaları Alfabetik Listele (BST)");
System.out.println("14. İsme Göre Hasta Ara (AVL - Dengeli)");
System.out.println("15. Hastaları Alfabetik Listele (AVL)");
System.out.println("16. AVL Ağacı İstatistikleri");
System.out.println("17. Bölüm İşlemleri");
System.out.println("18. Hastane Organizasyon Yapısı (Tree)");
System.out.println("0. Çıkış");
System.out.print("\nSeçiminiz: ");
int secim;
try {
secim = input.nextInt();
input.nextLine(); // Consume newline
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz girdi! Lütfen bir sayı girin.");
continue;
}
try {
switch (secim) {
case 1: registerNewPatient(); break;
case 2: registerNewDoctor(); break;
case 3: createAppointment(); break;
case 4: listPatients(); break;
case 5: listDoctors(); break;
case 6: listAppointments(); break;
case 7: showDoctorQueue(); break;
case 8: examinePatient(); break;
case 9: emergencyRoomMenu(); break;
case 10: showPatientHistory(); break;
case 11: undoLastOperation(); break;
case 12: searchPatientByName(); break;
case 13: patientBST.displayInOrder(); break;
case 14: searchPatientByNameAVL(); break;
case 15: patientAVL.displayInOrder(); break;
case 16: patientAVL.displayStats(); break;
case 17: departmentMenu(); break;
case 18: hospitalTree.displayHierarchy(); break;
case 0: return;
default: System.out.println(" Invalid choice!");
}
} catch (Exception e) {
System.out.println(" Error: " + e.getMessage());
}
}
}
/**
* Registers a new patient into the system.
* Updates Hash Table, BST, and AVL Tree simultaneously to keep data synchronized.
*/
void registerNewPatient() throws Exception {
if (patients.size() >= MAX_PATIENT_NUMBER) {
throw new Exception("Maximum patient capacity reached (" + MAX_PATIENT_NUMBER + ")!");
}
System.out.println("\n=== New Patient Registration ===");
System.out.print("First Name: ");
String firstName = input.nextLine();
System.out.print("Last Name: ");
String lastName = input.nextLine();
// Check for duplicates using BST Search
if (patientBST.search(firstName, lastName) != null) {
System.out.println("✗ A patient with this name already exists!");
return;
}
// Input Validation for National ID
String nationalId = "";
while (nationalId.length() != 11 || !nationalId.matches("\\d+")) {
System.out.print("National ID (11 digits): ");
nationalId = input.nextLine();
if (nationalId.length() != 11) {
System.out.println("✗ Must be 11 digits!");
} else if (!nationalId.matches("\\d+")) {
System.out.println("✗ Only numbers allowed!");
}
}
System.out.print("Phone: ");
String phone = input.nextLine();
// Input Validation for Date
LocalDate birthDate = null;
while (birthDate == null) {
try {
System.out.print("Birth Date (yyyy-MM-dd): ");
birthDate = LocalDate.parse(input.nextLine());
if (birthDate.isAfter(LocalDate.now())) {
System.out.println("✗ Birth date cannot be in the future!");
birthDate = null;
}
} catch (Exception e) {
System.out.println("✗ Invalid format! Use: yyyy-MM-dd (e.g., 1990-05-15)");
}
}
int newId = ++patientIdCounter;
Patient newPatient = new Patient(newId, firstName, lastName, nationalId, phone, birthDate);
// Add to all data structures
patients.put(newId, newPatient);
patientBST.insert(newPatient);
patientAVL.insert(newPatient);
// Log operation for Undo
undoStack.push("PATIENT_ADD:" + newId);
System.out.println("✓ Patient successfully registered! ID: " + newId);
}
/**
* Registers a new doctor and assigns them to a department.
* Updates the Hospital Tree hierarchy.
*/
void registerNewDoctor() throws Exception {
if (doctors.size() >= MAX_DOCTOR_NUMBER) {
throw new Exception("Maksimum doktor kapasitesine ulaşıldı (" + MAX_DOCTOR_NUMBER + ")!");
}
System.out.println("\n=== Yeni Doktor Kaydı ===");
System.out.print("Ad: ");
String firstName = input.nextLine();
System.out.print("Soyad: ");
String lastName = input.nextLine();
listDepartments();
System.out.print("\nBölüm ID (0 = Yeni bölüm oluştur): ");
int deptId;
try {
deptId = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz bölüm ID!");
return;
}
Department department;
if (deptId == 0) {
// Logic to create a new department on the fly
System.out.print("Yeni Bölüm Adı: ");
String deptName = input.nextLine();
System.out.print("Kapasite: ");
int capacity;
try {
capacity = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz kapasite değeri!");
return;
}
if (capacity <= 0) {
System.out.println("✗ Kapasite pozitif olmalı!");
return;
}
department = new Department(++departmentIdCounter, deptName, capacity);
departments.put(departmentIdCounter, department);
hospitalTree.addDepartmentToRoot(department);
System.out.println("✓ Yeni bölüm oluşturuldu!");
} else {
department = departments.get(deptId);
if (department == null) {
System.out.println("✗ Bölüm bulunamadı!");
return;
}
}
System.out.print("Telefon: ");
String phone = input.nextLine();
int newId = ++doctorIdCounter;
Doctor newDoctor = new Doctor(newId, firstName, lastName, department, phone);
// Try adding doctor to department (checks capacity)
if (department.addDoctor(newDoctor)) {
doctors.put(newId, newDoctor);
undoStack.push("DOCTOR_ADD:" + newId);
System.out.println("✓ Doktor kaydedildi! ID: " + newId);
System.out.println(" Bölüm: " + department.getName());
System.out.println(" Kalan kapasite: " + (department.getCapacity() - department.getDoctorCount()));
} else {
doctorIdCounter--;
System.out.println("✗ Bölüm dolu!");
System.out.println(" " + department.getName() + " bölümü kapasitesi: " +
department.getDoctorCount() + "/" + department.getCapacity());
}
}
// SEARCH METHODS
void searchPatientByName() {
System.out.println("\n Search Patient by Name (BST)");
System.out.print("First Name: ");
String firstName = input.nextLine();
System.out.print("Last Name: ");
String lastName = input.nextLine();
Patient found = patientBST.search(firstName, lastName);
if (found != null) {
displayPatientInfo(found);
} else {
System.out.println(" Patient not found!");
}
}
void searchPatientByNameAVL() {
System.out.println("\n Search Patient by Name (AVL) ");
System.out.print("First Name: ");
String firstName = input.nextLine();
System.out.print("Last Name: ");
String lastName = input.nextLine();
Patient found = patientAVL.search(firstName, lastName);
if (found != null) {
displayPatientInfo(found);
} else {
System.out.println(" Patient not found!");
}
}
void displayPatientInfo(Patient patient) {
System.out.println(" ID: " + patient.getId());
System.out.println(" Name: " + patient.getFirstName() + " " + patient.getLastName());
}
// LISTING METHODS
void listPatients() {
if (patients.isEmpty()) {
System.out.println("No registered patients.");
return;
}
for (Patient p : patients.values()) {
System.out.println("ID: " + p.getId() + " | " + p.getFirstName() + " " + p.getLastName());
}
}
void listDoctors() {
for (Doctor d : doctors.values()) {
System.out.println("ID: " + d.getId() + " | Dr. " + d.getFirstName() + " " + d.getLastName());
}
}
void listDepartments() {
for (Department d : departments.values()) {
System.out.println(d);
}
}
void listAppointments() {
for(Appointment a : appointments.values()) {
System.out.println(a);
}
}
void showPatientHistory() {
System.out.print("\nPatient ID: ");
int patientId = input.nextInt();
input.nextLine();
Patient patient = patients.get(patientId);
if (patient != null){
patient.printHistory();
} else {
System.out.println(" Patient not found!");
}
}
// DEPARTMENT OPERATIONS
void departmentMenu() {
while (true) {
System.out.println("\n");
System.out.println(" BÖLÜM İŞLEMLERİ ");
System.out.println(" ");
System.out.println("1. Tüm Bölümleri Listele");
System.out.println("2. Bölüm Doktorlarını Göster");
System.out.println("3. Yeni Bölüm Oluştur");
System.out.println("4. Bölüm Detaylarını Göster");
System.out.println("5. Bölüm İstatistikleri");
System.out.println("0. Ana Menüye Dön");
System.out.print("\nSeçiminiz: ");
int choice;
try {
choice = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz seçim!");
continue;
}
try {
switch (choice) {
case 1: listDepartmentsDetails(); break;
case 2: showDepartmentDoctorsMenu(); break;
case 3: createNewDepartment(); break;
case 4: showDepartmentDetails(); break;
case 5: showDepartmentStatistics(); break;
case 0: return;
default: System.out.println("✗ Geçersiz seçim!");
}
} catch (Exception e) {
System.out.println("✗ Hata: " + e.getMessage());
}
}
}
// APPOINTMENT & QUEUE OPERATIONS
/**
* Creates a new appointment with validation for time conflicts.
* Enqueues the patient to the doctor's daily FIFO queue.
*/
void createAppointment() {
System.out.println("\n=== Yeni Randevu Oluştur ===");
System.out.print("Hasta ID: ");
int patientId;
try {
patientId = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz hasta ID!");
return;
}
Patient patient = patients.get(patientId);
if (patient == null) {
System.out.println("✗ Hasta bulunamadı!");
return;
}
listDoctors();
System.out.print("Doktor ID: ");
int doctorId;
try {
doctorId = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz doktor ID!");
return;
}
Doctor doctor = doctors.get(doctorId);
if (doctor == null) {
System.out.println("✗ Doktor bulunamadı!");
return;
}
System.out.print("Tarih (yyyy-MM-dd): ");
String date = input.nextLine();
System.out.print("Saat (HH:mm): ");
String time = input.nextLine();
LocalDateTime appointmentTime;
try {
appointmentTime = LocalDateTime.parse(date + "T" + time);
} catch (Exception e) {
System.out.println("✗ Hata: Geçersiz tarih/saat formatı!");
return;
}
// --- CONFLICT CHECKS ---
if (isAppointmentInPast(appointmentTime)) {
System.out.println("✗ Hata: Geçmiş tarihe randevu oluşturulamaz!");
return;
}
if (doctorHasAppointmentAtTime(doctor, appointmentTime)) {
System.out.println("✗ Hata: Doktor bu saatte müsait değil!");
return;
}
if (patientHasAppointmentAtTime(patient, appointmentTime)) {
System.out.println("✗ Hata: Hastanın bu saatte zaten randevusu var!");
return;
}
// All checks passed - Create Appointment
try {
Appointment appointment = new Appointment(
++appointmentIdCounter,
patient,
doctor,
appointmentTime
);
appointments.put(appointmentIdCounter, appointment);
doctor.getDailyQueue().enqueue(appointment); // Add to FIFO queue
undoStack.push("APPOINTMENT_ADD:" + appointmentIdCounter);
System.out.println("\n✓ Randevu başarıyla oluşturuldu!");
System.out.println(" Randevu ID: " + appointmentIdCounter);
} catch (Exception e) {
System.out.println("✗ Beklenmeyen hata: " + e.getMessage());
appointmentIdCounter--;
}
}
void showDoctorQueue() {
System.out.print("Doctor ID: ");
Doctor doctor = doctors.get(input.nextInt());
if(doctor!=null) {
doctor.getDailyQueue().display();
}
}
/**
* Simulates the doctor examining the next patient in the queue.
* Dequeues the appointment and adds a visit record to the patient's history.
*/
void examinePatient() {
System.out.print("Doktor ID: ");
int doctorId = input.nextInt();
input.nextLine();
Doctor doctor = doctors.get(doctorId);
if (doctor == null) {
System.out.println("✗ Doktor bulunamadı!");
return;
}
// Remove patient from the front of the queue (FIFO)
Appointment appointment = doctor.getDailyQueue().dequeue();
if (appointment == null) {
System.out.println("✗ Kuyruk boş - muayene edilecek hasta yok.");
return;
}
System.out.println("\n=== Muayene Ediliyor ===");
System.out.println("Hasta: " + appointment.getPatient().getFirstName() + " " +
appointment.getPatient().getLastName());
System.out.print("Muayene Notları: ");
String notes = input.nextLine();
// Add to medical history linked list
appointment.getPatient().addVisit(
LocalDateTime.now(),
doctor,
notes
);
appointment.setStatus("Completed");
System.out.println("\n✓ Muayene tamamlandı!");
}
private int getQueueSize(AppointmentQueue queue) {
return queue.size();
}
// EMERGENCY ROOM (TRIAGE) OPERATIONS
void emergencyRoomMenu() {
System.out.println("\n=== Acil Servis İşlemleri ===");
System.out.println("1. Yeni Hasta Kabul Et");
System.out.println("2. En Acil Hastayı Tedavi Et");
System.out.println("3. Acil Servis Kuyruğunu Göster");
System.out.println("4. Acil Servisten Hasta Sil");
System.out.println("0. Ana Menüye Dön");
System.out.print("\nSeçiminiz: ");
int choice;
try {
choice = input.nextInt();
input.nextLine();
} catch (Exception e) {
input.nextLine();
System.out.println("✗ Geçersiz seçim!");
return;
}
if (choice == 1) {
// Add Patient to ER
System.out.print("Hasta ID: ");
int patientId = input.nextInt();
input.nextLine();
Patient patient = patients.get(patientId);
if (patient == null) {
System.out.println("✗ Hasta bulunamadı!");
return;
}
System.out.print("Önem Derecesi (1-10, 10=en acil): ");
int severity = input.nextInt();
input.nextLine();
if (severity < 1 || severity > 10) {
System.out.println("✗ Önem derecesi 1-10 arasında olmalı!");
return;
}
System.out.print("Şikayet/Semptomlar: ");
String complaint = input.nextLine().trim();
// Add to Priority Queue (Max-Heap)
ERPriorityQueue.ERPatient erPatient =
new ERPriorityQueue.ERPatient(patient, severity, complaint);
erQueue.addPatient(erPatient);
undoStack.push("ER_ADD", erPatient);
System.out.println("\n✓ Hasta acil servise kabul edildi!");
} else if (choice == 2) {
// Treat Highest Priority Patient
ERPriorityQueue.ERPatient erPatient = erQueue.removeHighestPriority();
if (erPatient == null) {
System.out.println("✗ Acil serviste hasta yok.");
return;
}
System.out.println("\n=== Tedavi Ediliyor ===");
System.out.println("Hasta: " + erPatient.getPatient().getFirstName());
System.out.println("Önem: " + erPatient.getSeverity() + "/10");
// ... (Treatment logic and logging visit) ...
System.out.println("✓ Tedavi tamamlandı!");
} else if (choice == 3) {
erQueue.display();
} else if (choice == 4) {
deleteERPatient();
} else if (choice == 0) {
return;
} else {
System.out.println("✗ Geçersiz seçim!");
}
}
void deleteERPatient() {
if (erQueue.isEmpty()) {
System.out.println("✗ Acil servis kuyruğu boş!");
return;
}
erQueue.display();
System.out.print("\nSilinecek Hasta ID'si: ");
int patientId = input.nextInt();
input.nextLine();
boolean removed = erQueue.removePatientById(patientId);
if (removed) {
System.out.println("\n✓ Hasta acil servis kuyruğundan silindi!");
} else {
System.out.println("\n✗ Bu ID'ye sahip hasta bulunamadı!");
}
}
// ============================================
// UNDO OPERATIONS
// ============================================
/**
* Reverts the last "Add" operation performed.
* Uses a Stack (LIFO) to track history.
*/
void undoLastOperation() {
if (undoStack.isEmpty()) {
System.out.println("Geri alınacak işlem yok.");
return;
}
// Pop last operation from Stack
UndoStack.StackNode node = undoStack.popWithData();
String op = node.operation;
String[] parts = op.split(":");
// UNDO PATIENT ADD
if (parts[0].equals("PATIENT_ADD")) {
int patientId = Integer.parseInt(parts[1]);
Patient patient = patients.get(patientId);
if (patient == null) return;
// Remove associated appointments first
ArrayList<Integer> appointmentIdsToRemove = new ArrayList<>();
for (Appointment app : appointments.values()) {
if (app.getPatient().getId() == patientId) {
appointmentIdsToRemove.add(app.getId());
}
}
for (int appId : appointmentIdsToRemove) {
Appointment app = appointments.get(appId);
if (app != null) {
removeAppointmentFromQueue(app.getDoctor().getDailyQueue(), appId);
appointments.remove(appId);
}
}
// Remove patient from all data structures
patients.remove(patientId);
patientBST.delete(patient.getFirstName(), patient.getLastName());
patientAVL.delete(patient.getFirstName(), patient.getLastName());
if (patientId == patientIdCounter) patientIdCounter--;
System.out.println("✓ Geri alma: Hasta ve randevuları silindi.");
}
// UNDO DOCTOR ADD
else if (parts[0].equals("DOCTOR_ADD")) {
int doctorId = Integer.parseInt(parts[1]);
Doctor doctor = doctors.get(doctorId);
if (doctor == null) return;
// Clean up doctor's queue and appointments
while (!doctor.getDailyQueue().isEmpty()) {
doctor.getDailyQueue().dequeue();
}
doctor.getDepartment().getDoctors().remove(doctor);
doctors.remove(doctorId);
if (doctorId == doctorIdCounter) doctorIdCounter--;
System.out.println("✓ Geri alma: Doktor silindi.");
}
// UNDO APPOINTMENT ADD
else if (parts[0].equals("APPOINTMENT_ADD")) {
int appointmentId = Integer.parseInt(parts[1]);
Appointment appointment = appointments.get(appointmentId);
if (appointment == null) return;
Doctor doctor = appointment.getDoctor();
removeAppointmentFromQueue(doctor.getDailyQueue(), appointmentId);
appointments.remove(appointmentId);
if (appointmentId == appointmentIdCounter) appointmentIdCounter--;
System.out.println("✓ Geri alma: Randevu silindi.");
}
// UNDO ER ADD
else if (parts[0].equals("ER_ADD")) {
Object data = node.data;
if (data instanceof ERPriorityQueue.ERPatient) {
ERPriorityQueue.ERPatient erPatient = (ERPriorityQueue.ERPatient) data;
boolean removed = erQueue.removePatientById(erPatient.getPatient().getId());
if (removed) System.out.println("✓ Geri alma: Acil servis hastası silindi.");
}
}
}
// Helper: Removes a specific appointment from a doctor's queue without breaking FIFO order.
private void removeAppointmentFromQueue(AppointmentQueue queue, int appointmentId) {
if (queue.isEmpty()) return;
AppointmentQueue tempQueue = new AppointmentQueue();
boolean found = false;
while (!queue.isEmpty()) {
Appointment current = queue.dequeue();
if (current.getId() != appointmentId) {
tempQueue.enqueue(current);
} else {
found = true;
}
}
while (!tempQueue.isEmpty()) {
queue.enqueue(tempQueue.dequeue());
}
}
// INITIALIZATION & UTILS
void loadInitialSampleData() {
System.out.println("Hash Table Capacity based on Student ID: " + ((STUDENT_ID % 100) + 50));
System.out.println("\n=== Loading Sample Data ===");
System.out.println("Student ID: " + STUDENT_ID);
System.out.println("Appointment Duration: " + (15 + (STUDENT_ID % 5)) + " minutes");
// Create departments
Department cardiology = new Department(++departmentIdCounter, "Cardiology", 5);
departments.put(departmentIdCounter, cardiology);
hospitalTree.addDepartmentToRoot(cardiology);
Department neurology = new Department(++departmentIdCounter, "Neurology", 4);
departments.put(departmentIdCounter, neurology);
hospitalTree.addDepartmentToRoot(neurology);
Department emergency = new Department(++departmentIdCounter, "Emergency Medicine", 8);
departments.put(departmentIdCounter, emergency);
hospitalTree.addDepartmentToRoot(emergency);
// Create Doctors
Doctor d1 = new Doctor(++doctorIdCounter, "Mehmet", "Yilmaz", cardiology, "0532-111-2233");
cardiology.addDoctor(d1);
doctors.put(doctorIdCounter, d1);
Doctor d4 = new Doctor(++doctorIdCounter, "Semih", "Arslan", emergency, "0535-444-5566");
emergency.addDoctor(d4);
doctors.put(doctorIdCounter, d4);
// Create Patients
Patient p1 = new Patient(++patientIdCounter, "Ahmet", "Oz", "12345678901", "0535-444-5566", LocalDate.of(1985, 5, 15));
patients.put(patientIdCounter, p1);
patientBST.insert(p1);
patientAVL.insert(p1);
// Add history
p1.addVisit(LocalDateTime.of(2024, 10, 15, 10, 30), d1, "Annual checkup");
System.out.println("\n✓ Sample data loaded successfully!");
}
// Helper methods for displaying detailed department info
void listDepartmentsDetails() {
if (departments.isEmpty()) {
System.out.println("No departments yet.");
return;
}
System.out.println("\n=== All Departments ===");
for (Department department : departments.values()) {
int remaining = department.getCapacity() - department.getDoctorCount();
System.out.println("ID: " + department.getId() +
" | " + department.getName() +
" | Doctors: " + department.getDoctorCount() + "/" + department.getCapacity() +
" | Remaining capacity: " + remaining);
}
}
void showDepartmentDoctorsMenu(){
if(departments.isEmpty()) return;
listDepartments();
System.out.print("\nDepartment ID: ");
try {
int departmentId=input.nextInt();
Department department=departments.get(departmentId);
if(department!=null) {
hospitalTree.showDepartmentDoctors(department);
} else {
System.out.println("Department not found!");
}
} catch(Exception e){
System.out.println("error invalid choice");
}
}
void showDepartmentStatistics(){
if (departments.isEmpty()) return;
System.out.println("\n=== Department Statistics ===");
int totalCapacity = 0;
int totalDoctors = 0;
for (Department d : departments.values()) {
totalCapacity += d.getCapacity();
totalDoctors += d.getDoctorCount();
}
System.out.println("Total Departments: " + departments.size());
System.out.println("Total Capacity: " + totalCapacity);
System.out.println("Total Doctors: " + totalDoctors);
}
void showDepartmentDetails() {
if (departments.isEmpty()) {
return;
}
listDepartments();
System.out.print("Department ID: ");
try {
int deptId = input.nextInt();
input.nextLine();
Department dept = departments.get(deptId);
if (dept == null) {
return;
}
System.out.println("=== Department Details ===");
System.out.println("ID: " + dept.getId());
System.out.println("Name: " + dept.getName());
if (!dept.getDoctors().isEmpty()) {
System.out.println("\nDoctors:");
for (Doctor doc : dept.getDoctors()) {
System.out.println(" - Dr. " + doc.getFirstName() + " " + doc.getLastName());
}
}
} catch (Exception e) {
input.nextLine();
}
}
void createNewDepartment() {
System.out.println("=== Create New Department ===");
System.out.print("Department Name: ");
String name = input.nextLine().trim();
System.out.print("Capacity: ");
try {
int capacity = input.nextInt();
input.nextLine();
if (capacity <= 0) return;
Department newDept = new Department(++departmentIdCounter, name, capacity);
departments.put(departmentIdCounter, newDept);
hospitalTree.addDepartmentToRoot(newDept);
System.out.println("Department created! ID: " + departmentIdCounter);
} catch (Exception e) {
input.nextLine();
}
}
// UTILITY: CONFLICT CHECKING
private boolean appointmentsOverlap(LocalDateTime start1, LocalDateTime end1, LocalDateTime start2, LocalDateTime end2) {
return start1.isBefore(end2) && start2.isBefore(end1);
}
private boolean doctorHasAppointmentAtTime(Doctor doctor, LocalDateTime appointmentTime) {