LearnFrenzy
Sign in Take a free test

Encapsulation · Encapsulation Programs · Question 9

Parking meter with private time and coins in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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());
    }
}

Output Verified by compiling and running

true false true true false
3h 0m, collected Rs 60
0h 30m, collected Rs 60 expired=false
0h 0m, collected Rs 60 expired=true

Three ₹20 coins reach the 180-minute cap, so the ₹10 coin is refused rather than wasted.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links