Model a parking lot with a fixed number of slots: park vehicles (number, type), refuse when full, unpark by number with a fee based on hours (bike ₹10/h, car ₹30/h), and print the status.
Solution
Main.java
class Vehicle {
final String number, type;
final int inHour;
Vehicle(String number, String type, int inHour) { this.number = number; this.type = type; this.inHour = inHour; }
}
class ParkingLot {
private final Vehicle[] slots;
ParkingLot(int n) { slots = new Vehicle[n]; }
String park(Vehicle v) {
for (int i = 0; i < slots.length; i++) {
if (slots[i] == null) { slots[i] = v; return v.number + " -> slot " + (i + 1); }
}
return v.number + ": lot full";
}
String unpark(String number, int outHour) {
for (int i = 0; i < slots.length; i++) {
Vehicle v = slots[i];
if (v != null && v.number.equals(number)) {
slots[i] = null;
int hours = Math.max(1, outHour - v.inHour);
int fee = hours * (v.type.equals("bike") ? 10 : 30);
return number + " left slot " + (i + 1) + ", " + hours + "h, fee Rs " + fee;
}
}
return number + ": not found";
}
String status() {
StringBuilder sb = new StringBuilder();
for (Vehicle v : slots) sb.append(v == null ? "[ ]" : "[" + v.type.charAt(0) + "]");
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
ParkingLot lot = new ParkingLot(3);
System.out.println(lot.park(new Vehicle("MH12-1111", "car", 9)));
System.out.println(lot.park(new Vehicle("MH12-2222", "bike", 10)));
System.out.println(lot.park(new Vehicle("MH12-3333", "car", 10)));
System.out.println(lot.park(new Vehicle("MH12-4444", "bike", 11)));
System.out.println(lot.unpark("MH12-1111", 13));
System.out.println(lot.park(new Vehicle("MH12-4444", "bike", 13)));
System.out.println(lot.unpark("MH12-9999", 14) + " | " + lot.status());
}
}
Output Verified by compiling and running
MH12-1111 -> slot 1
MH12-2222 -> slot 2
MH12-3333 -> slot 3
MH12-4444: lot full
MH12-1111 left slot 1, 4h, fee Rs 120
MH12-4444 -> slot 1
MH12-9999: not found | [b][b][c]
The slots array holds references to Vehicle objects (null when free). Unparking sets the slot back to null, freeing it for the next vehicle.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!