-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.java
More file actions
625 lines (569 loc) · 25 KB
/
Copy pathmain.java
File metadata and controls
625 lines (569 loc) · 25 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
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
// Custom Exception for Invalid Vehicle Type
class InvalidVehicleTypeException extends Exception {
public InvalidVehicleTypeException(String message) {
super(message);
}
}
// Custom Exception for Invalid Parking Slot Input
class InvalidSlotException extends Exception {
public InvalidSlotException(String message) {
super(message);
}
}
// Custom Exception for Invalid Price Input
class InvalidPriceException extends Exception {
public InvalidPriceException(String message) {
super(message);
}
}
// Custom Exception for Empty Parking History
class EmptyParkingHistoryException extends Exception {
public EmptyParkingHistoryException(String message) {
super(message);
}
}
// Interface enforcing basic parking operations
interface ParkingOperations {
void enterSlots();
void enterPrices();
void displayDetails();
}
// Abstract class providing a template for all vehicles
abstract class Vehicle implements ParkingOperations {
private String vehicleType;
private int[] slots = new int[3]; // [General, VIP, Handicapped]
private Map<String, Double> priceMap = new LinkedHashMap<>();
Scanner sc=new Scanner(System.in);
protected final String[] durations = {"1hr", "3hr", "5hr", "8hr", "12hr", "24hr"};
public Vehicle(String type, Scanner sc) {
this.vehicleType = type;
this.sc = sc;
}
public String getVehicleType() {
return vehicleType;
}
public int[] getSlots() {
return slots;
}
public void setSlot(int category, int value) {
slots[category] = value;
}
public Map<String, Double> getPriceMap() {
return priceMap;
}
public void setPrice(String duration, double price) {
priceMap.put(duration, price);
}
// Enforced by interface
public abstract void enterSlots();
public abstract void enterPrices();
public void displayDetails() {
System.out.println("\nVehicle: " + vehicleType);
System.out.println(" Slots → General: " + slots[0] + ", VIP: " + slots[1] + ", Handicapped: " + slots[2]);
System.out.println(" Parking Prices:");
for (String duration : durations) {
System.out.printf(" %s: Rs %.2f\n", duration, priceMap.getOrDefault(duration, 0.0));
}
}
}
// Concrete class that extends the abstract class
class SpecificVehicle extends Vehicle {
public SpecificVehicle(String type, Scanner sc) {
super(type, sc);
}
@Override
public void enterSlots() {
try {
System.out.println("\nEnter slot details for " + getVehicleType());
System.out.print("General: ");
int general = sc.nextInt();
if (general < 0) throw new InvalidSlotException("Invalid number of General slots. Must be a positive integer.");
setSlot(0, general);
System.out.print("VIP: ");
int vip = sc.nextInt();
if (vip < 0) throw new InvalidSlotException("Invalid number of VIP slots. Must be a positive integer.");
setSlot(1, vip);
System.out.print("Handicapped: ");
int handicapped = sc.nextInt();
if (handicapped < 0) throw new InvalidSlotException("Invalid number of Handicapped slots. Must be a positive integer.");
setSlot(2, handicapped);
sc.nextLine(); // consume newline
} catch (InputMismatchException e) {
System.out.println("Error: Please enter valid integer values for the slots.");
sc.nextLine(); // clear the invalid input
} catch (InvalidSlotException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error while entering slot details: " + e.getMessage());
}
}
public void enterPrices() {
try {
System.out.println("Enter prices for " + getVehicleType());
for (String duration : durations) {
System.out.print("Price for " + duration + ": Rs ");
double price = sc.nextDouble();
if (price < 0) throw new InvalidPriceException("Price must be a positive value.");
setPrice(duration, price);
}
sc.nextLine();
} catch (InputMismatchException e) {
System.out.println("Error: Please enter valid numeric values for prices.");
sc.nextLine();
} catch (InvalidPriceException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error while entering price details: " + e.getMessage());
}
}
}
// Organisation class manages multiple Vehicles and parking
class Organisation {
private String name;
private List<Vehicle> vehicles = new ArrayList<>();
// Map vehicleType to VehicleSlotInfo with slots per category count
private Map<String, VehicleSlotInfo> vehicleSlots = new HashMap<>();
private Map<String, VehicleParkingInfo> parkedVehicles = new HashMap<>();
private List<String> parkingHistory = new ArrayList<>();
private final String[] durations = {"1hr", "3hr", "5hr", "8hr", "12hr", "24hr"};
public Organisation(String name) {
this.name = name;
this.parkingHistory = new ArrayList<>();
}
public String getName() {
return name;
}
public void addOrUpdateVehicles(Scanner sc) {
boolean more = true;
while (more) {
try {
String vehicleType = getVehicleTypeChoice(sc);
if (vehicleType != null && !vehicleType.isBlank()) {
Optional<Vehicle> existingVehicleOpt = vehicles.stream()
.filter(v -> v.getVehicleType().equalsIgnoreCase(vehicleType))
.findFirst();
Vehicle vehicle;
if (existingVehicleOpt.isPresent()) {
vehicle = existingVehicleOpt.get();
System.out.println("Updating slots and prices for " + vehicleType);
} else {
vehicle = new SpecificVehicle(vehicleType, sc);
vehicles.add(vehicle);
}
vehicle.enterSlots();
vehicle.enterPrices();
int[] slotsArray = vehicle.getSlots();
double baseRate = vehicle.getPriceMap().getOrDefault("1hr", 0.0);
// Store slots per category
vehicleSlots.put(vehicleType, new VehicleSlotInfo(slotsArray[0], slotsArray[1], slotsArray[2], baseRate,
vehicleSlots.containsKey(vehicleType) ? vehicleSlots.get(vehicleType).occupiedGeneralSlots : 0,
vehicleSlots.containsKey(vehicleType) ? vehicleSlots.get(vehicleType).occupiedVIPSlots : 0,
vehicleSlots.containsKey(vehicleType) ? vehicleSlots.get(vehicleType).occupiedHandicappedSlots : 0));
}
} catch (InvalidVehicleTypeException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
}
System.out.print("\nDo you want to add/update another vehicle type? (yes/no): ");
String answer = sc.nextLine();
more = answer.equalsIgnoreCase("yes");
}
}
private String getVehicleTypeChoice(Scanner sc) throws InvalidVehicleTypeException {
try {
System.out.println("\nChoose vehicle type:");
System.out.println("1. Bike");
System.out.println("2. Scooter");
System.out.println("3. Bicycle");
System.out.println("4. Car");
System.out.println("5. Bus");
System.out.println("6. Truck");
System.out.println("7. Other");
System.out.print("Enter choice (1-7): ");
int ch = sc.nextInt();
sc.nextLine();
return switch (ch) {
case 1 -> "Bike";
case 2 -> "Scooter";
case 3 -> "Bicycle";
case 4 -> "Car";
case 5 -> "Bus";
case 6 -> "Truck";
case 7 -> {
System.out.print("Enter custom vehicle type: ");
yield sc.nextLine();
}
default -> throw new InvalidVehicleTypeException("Invalid vehicle type choice.");
};
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter number 1-7.");
sc.nextLine();
return null;
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
return null;
}
}
public void showSummary() {
System.out.println("\n--- Summary for Organisation: " + name + " ---");
for (Vehicle v : vehicles) {
v.displayDetails();
}
}
public int getTotalAvailableSlots() {
int totalAvailable = 0;
for (VehicleSlotInfo slotInfo : vehicleSlots.values()) {
totalAvailable += (slotInfo.generalSlots - slotInfo.occupiedGeneralSlots);
totalAvailable += (slotInfo.vipSlots - slotInfo.occupiedVIPSlots);
totalAvailable += (slotInfo.handicappedSlots - slotInfo.occupiedHandicappedSlots);
}
return totalAvailable;
}
public boolean hasAvailableSlot(String vehicleType, String slotCategory) {
VehicleSlotInfo slotInfo = vehicleSlots.get(vehicleType);
if (slotInfo == null) return false;
return switch (slotCategory.toLowerCase()) {
case "general" -> slotInfo.generalSlots > slotInfo.occupiedGeneralSlots;
case "vip" -> slotInfo.vipSlots > slotInfo.occupiedVIPSlots;
case "handicapped" -> slotInfo.handicappedSlots > slotInfo.occupiedHandicappedSlots;
default -> false;
};
}
public double getRate(String vehicleType) {
VehicleSlotInfo slotInfo = vehicleSlots.get(vehicleType);
return slotInfo == null ? -1 : slotInfo.ratePerHour;
}
// Overloaded parkVehicle to include slot category
public void parkVehicle(String vehicleNumber, String name, String contact, String vehicleType, double ratePerHour, String slotCategory) {
VehicleParkingInfo info = new VehicleParkingInfo(name, contact, vehicleType, ratePerHour, LocalDateTime.now(), slotCategory);
parkedVehicles.put(vehicleNumber, info);
VehicleSlotInfo slotInfo = vehicleSlots.get(vehicleType);
if (slotInfo != null) {
switch (slotCategory.toLowerCase()) {
case "general" -> slotInfo.occupiedGeneralSlots++;
case "vip" -> slotInfo.occupiedVIPSlots++;
case "handicapped" -> slotInfo.occupiedHandicappedSlots++;
}
}
String logEntry = LocalDateTime.now() + " - Parked Vehicle: " + vehicleNumber + ", Type: " + vehicleType +
", Owner: " + name + ", Slot: " + slotCategory;
parkingHistory.add(logEntry);
System.out.println("Vehicle parked successfully in organisation " + name + " in " + slotCategory + " slot.");
}
public boolean isVehicleParked(String vehicleNumber) {
return parkedVehicles.containsKey(vehicleNumber);
}
public void unparkVehicle(String vehicleNumber) {
VehicleParkingInfo info = parkedVehicles.remove(vehicleNumber);
if (info == null) return;
VehicleSlotInfo slotInfo = vehicleSlots.get(info.vehicleType);
if (slotInfo != null) {
switch (info.slotCategory.toLowerCase()) {
case "general" -> slotInfo.occupiedGeneralSlots--;
case "vip" -> slotInfo.occupiedVIPSlots--;
case "handicapped" -> slotInfo.occupiedHandicappedSlots--;
}
}
LocalDateTime exitTime = LocalDateTime.now();
String logEntry = exitTime + " - Unparked Vehicle: " + vehicleNumber + ", Type: " + info.vehicleType +
", Owner: " + info.name + ", Slot: " + info.slotCategory;
parkingHistory.add(logEntry);
LocalDateTime entryTime = info.entryTime;
long hoursParked = Math.max(1, Duration.between(entryTime, exitTime).toHours());
double baseFare = info.ratePerHour * hoursParked;
System.out.println("\n--- Parking Receipt ---");
System.out.println("Vehicle Number : " + vehicleNumber);
System.out.println("Name : " + info.name);
System.out.println("Contact : " + info.contact);
System.out.println("Vehicle Type : " + info.vehicleType);
System.out.println("Slot Category : " + info.slotCategory);
System.out.println("Entry Time : " + entryTime);
System.out.println("Exit Time : " + exitTime);
System.out.println("Hours Parked : " + hoursParked);
System.out.printf("Total Fare : Rs %.2f\n", baseFare);
}
public void searchVehicle(String vehicleNumber) {
if (isVehicleParked(vehicleNumber)) {
System.out.println(vehicleNumber + " is currently parked in organisation " + name + ".");
} else {
System.out.println(vehicleNumber + " is not parked in organisation " + name + ".");
}
}
public void showParkingHistory() throws EmptyParkingHistoryException {
if (parkingHistory == null || parkingHistory.isEmpty()) {
throw new EmptyParkingHistoryException("No parking history records available.");
}
System.out.println("\n--- Parking History for Organisation: " + name + " ---");
for (String record : parkingHistory) {
System.out.println(record);
}
}
private static class VehicleParkingInfo {
String name;
String contact;
String vehicleType;
double ratePerHour;
LocalDateTime entryTime;
String slotCategory;
public VehicleParkingInfo(String name, String contact, String vehicleType, double ratePerHour, LocalDateTime entryTime, String slotCategory) {
this.name = name;
this.contact = contact;
this.vehicleType = vehicleType;
this.ratePerHour = ratePerHour;
this.entryTime = entryTime;
this.slotCategory = slotCategory;
}
}
private static class VehicleSlotInfo {
int generalSlots;
int vipSlots;
int handicappedSlots;
double ratePerHour;
int occupiedGeneralSlots;
int occupiedVIPSlots;
int occupiedHandicappedSlots;
public VehicleSlotInfo(int generalSlots, int vipSlots, int handicappedSlots, double ratePerHour,
int occupiedGeneralSlots, int occupiedVIPSlots, int occupiedHandicappedSlots) {
this.generalSlots = generalSlots;
this.vipSlots = vipSlots;
this.handicappedSlots = handicappedSlots;
this.ratePerHour = ratePerHour;
this.occupiedGeneralSlots = occupiedGeneralSlots;
this.occupiedVIPSlots = occupiedVIPSlots;
this.occupiedHandicappedSlots = occupiedHandicappedSlots;
}
}
}
public class main {
private static Map<String, Organisation> organisations = new HashMap<>();
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("=== Welcome to the Smart Parking System ===");
while (true) {
System.out.println("\nAre you from an Organisation or Parking? (Enter 'organisation' or 'parking')");
String userType = scanner.nextLine().trim();
if (userType.equalsIgnoreCase("organisation")) {
handleOrganisation();
} else if (userType.equalsIgnoreCase("parking")) {
if (organisations.isEmpty()) {
System.out.println("No organisations registered yet. Please ask an organisation to register first.");
} else {
handleParking();
}
} else {
System.out.println("Invalid choice. Please select either 'organisation' or 'parking'.");
continue;
}
System.out.println("\nDo you want to continue? (yes/no)");
String cont = scanner.nextLine();
if (cont.equalsIgnoreCase("no")) {
System.out.println("Thank you for using the Parking System!");
break;
}
}
scanner.close();
}
private static void handleOrganisation() {
System.out.print("Enter the name of your organisation: ");
String orgName = scanner.nextLine().trim();
if (orgName.isEmpty()) {
System.out.println("Organisation name cannot be empty.");
return;
}
Organisation org = organisations.get(orgName);
if (org == null) {
org = new Organisation(orgName);
organisations.put(orgName, org);
}
boolean continueOrg = true;
while (continueOrg) {
System.out.println("\nOrganisation Menu - Select an option:");
System.out.println("1. Add/Update Vehicle Slots and Prices");
System.out.println("2. Search for a Parked Vehicle");
System.out.println("3. Show Vehicle Slots and Prices Summary");
System.out.println("4. Show Parking History");
System.out.println("5. Exit Organisation Menu");
int choice = getIntInput("Enter choice: ");
switch (choice) {
case 1 -> org.addOrUpdateVehicles(scanner);
case 2 -> {
System.out.print("Enter Vehicle Number to search: ");
String vehicleNo = scanner.nextLine();
org.searchVehicle(vehicleNo);
}
case 3 -> org.showSummary();
case 4 -> {
try {
org.showParkingHistory();
} catch (EmptyParkingHistoryException e) {
System.out.println("Error: " + e.getMessage());
}
}
case 5 -> continueOrg = false;
default -> System.out.println("Invalid choice. Please select 1-5.");
}
}
}
private static void handleParking() {
System.out.print("Enter the name of your organisation: ");
String orgName = scanner.nextLine();
Organisation organisation = organisations.get(orgName);
if (organisation == null) {
System.out.println("Organisation not found.");
return;
}
int availableSlots = organisation.getTotalAvailableSlots();
if (availableSlots <= 0) {
System.out.println("No available slots in this organisation.");
return;
}
boolean continueParking = true;
while (continueParking) {
System.out.println("\nAvailable Slots in " + orgName + ": " + availableSlots);
System.out.println("1. Park");
System.out.println("2. Unpark");
System.out.println("3. Search Parked Vehicle");
System.out.println("4. Exit Parking Menu");
int choice = getIntInput("Choose an option: ");
try {
switch (choice) {
case 1 -> {
parkVehicle(organisation);
availableSlots = organisation.getTotalAvailableSlots();
}
case 2 -> {
unparkVehicle(organisation);
availableSlots = organisation.getTotalAvailableSlots();
}
case 3 -> {
System.out.print("Enter Vehicle Number to search: ");
String vehicleNo = scanner.nextLine();
organisation.searchVehicle(vehicleNo);
}
case 4 -> continueParking = false;
default -> System.out.println("Invalid choice.");
}
} catch (ParkingException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
private static void parkVehicle(Organisation organisation) throws ParkingException {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your contact: ");
String contact = scanner.nextLine();
validateContactNumber(contact);
System.out.print("Enter vehicle number: ");
String vehicleNumber = scanner.nextLine();
if (organisation.isVehicleParked(vehicleNumber)) {
throw new ParkingException("This vehicle is already parked in this organisation.");
}
String vehicleType = chooseVehicleType();
double rate = organisation.getRate(vehicleType);
if (rate < 0) {
throw new ParkingException("Vehicle type not supported for parking in this organisation.");
}
// Ask user for the type of slot they want to park in
String slotCategory = chooseSlotCategory();
if (!organisation.hasAvailableSlot(vehicleType, slotCategory)) {
throw new ParkingException("No " + slotCategory + " slots available for " + vehicleType + " in this organisation.");
}
organisation.parkVehicle(vehicleNumber, name, contact, vehicleType, rate, slotCategory);
System.out.println("\n--- Parking Slot Allotted ---");
generateReceipt(name, contact, vehicleNumber, vehicleType, rate);
}
private static void unparkVehicle(Organisation organisation) throws ParkingException {
System.out.print("Enter your vehicle number to unpark: ");
String vehicleNumber = scanner.nextLine();
if (!organisation.isVehicleParked(vehicleNumber)) {
throw new ParkingException("Vehicle not found in this organisation.");
}
organisation.unparkVehicle(vehicleNumber);
}
private static void validateContactNumber(String contact) throws ParkingException {
if (!contact.matches("\\d{10}")) {
throw new ParkingException("Contact number must be exactly 10 digits.");
}
}
private static String chooseVehicleType() {
System.out.println("\nSelect Vehicle Type:");
System.out.println("1. Bike");
System.out.println("2. Scooter");
System.out.println("3. Bicycle");
System.out.println("4. Car");
System.out.println("5. Bus");
System.out.println("6. Truck");
System.out.println("7. Other");
System.out.print("Choice: ");
int choice = getIntInput("");
return switch (choice) {
case 1 -> "Bike";
case 2 -> "Scooter";
case 3 -> "Bicycle";
case 4 -> "Car";
case 5 -> "Bus";
case 6 -> "Truck";
case 7 -> {
System.out.print("Enter custom vehicle type: ");
yield scanner.nextLine();
}
default -> {
System.out.println("Invalid choice, defaulting to 'Other'");
yield "Other";
}
};
}
private static String chooseSlotCategory() {
System.out.println("\nSelect Slot Category:");
System.out.println("1. General");
System.out.println("2. VIP");
System.out.println("3. Handicapped");
System.out.print("Choice: ");
int choice = getIntInput("");
return switch (choice) {
case 1 -> "General";
case 2 -> "VIP";
case 3 -> "Handicapped";
default -> {
System.out.println("Invalid choice, defaulting to 'General'");
yield "General";
}
};
}
private static void generateReceipt(String name, String contact, String vehicleNumber,
String vehicleType, double rate) {
LocalDateTime entryTime = LocalDateTime.now();
System.out.println("\n--- Entry Receipt ---");
System.out.println("Name : " + name);
System.out.println("Contact : " + contact);
System.out.println("Vehicle Number : " + vehicleNumber);
System.out.println("Vehicle Type : " + vehicleType);
System.out.printf("Rate per Hour : Rs %.2f\n", rate);
System.out.println("Entry Time : " + entryTime);
}
private static int getIntInput(String prompt) {
int value;
while (true) {
try {
if (!prompt.isEmpty()) {
System.out.print(prompt);
}
value = Integer.parseInt(scanner.nextLine().trim());
break;
} catch (NumberFormatException e) {
System.out.println("Enter a valid number.");
}
}
return value;
}
public static class ParkingException extends Exception {
public ParkingException(String message) {
super(message);
}
}
}