Write a ParkingMeter that accepts only ₹5, ₹10 and ₹20 coins (₹10 = 30 minutes), caps time at 3 hours, counts down with tick(minutes), and reports remaining time and collected money.
Solution
Main.java
class ParkingMeter {
private static final int MAX_MINUTES = 180;
private int minutesLeft;
private int collected;
public boolean insert(int coin) {
if (coin != 5 && coin != 10 && coin != 20) return false;
if (minutesLeft >= MAX_MINUTES) return false;
collected += coin;
minutesLeft = Math.min(MAX_MINUTES, minutesLeft + coin * 3);
return true;
}
public void tick(int minutes) { minutesLeft = Math.max(0, minutesLeft - minutes); }
public boolean expired() { return minutesLeft == 0; }
public String status() { return minutesLeft / 60 + "h " + minutesLeft % 60 + "m, collected Rs " + collected; }
}
public class Main {
public static void main(String[] args) {
ParkingMeter m = new ParkingMeter();
System.out.println(m.insert(20) + " " + m.insert(2) + " " + m.insert(20) + " " + m.insert(20) + " " + m.insert(10));
System.out.println(m.status());
m.tick(150);
System.out.println(m.status() + " expired=" + m.expired());
m.tick(45);
System.out.println(m.status() + " expired=" + m.expired());
}
}
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!