Facebook Pixel

Exercise: Encapsulation

This exercise puts the encapsulation lesson into code.

Scenario

Model a bank account whose balance is private and starts at zero. Callers never touch the balance directly — every change goes through a method that validates the request first. The account is driven by a list of commands, and each command produces exactly one output line.

Commands

The program reads one command per line and prints one line of output per command.

CommandBehaviorOutput
["deposit", amount]Add amount to the balance"Balance: <bal>", or "Invalid amount" if amount <= 0
["withdraw", amount]Subtract amount from the balance"Balance: <bal>", or "Invalid amount" if amount <= 0, or "Insufficient funds" if amount exceeds the balance
["balance"]Report the current balance"Balance: <bal>"

Amounts are integers. The balance never goes negative, because withdraw rejects any amount it cannot cover.

Example
Input
7
deposit 100
deposit -50
withdraw 30
balance
withdraw 200
withdraw 70
balance
Output
Balance: 100
Invalid amount
Balance: 70
Balance: 70
Insufficient funds
Balance: 0
Balance: 0
Explanation
Depositing 100 sets the balance to 100. Depositing -50 fails validation and returns "Invalid amount" without changing anything. Withdrawing 30 leaves a balance of 70. The `balance` query confirms 70. Withdrawing 200 exceeds the balance and returns "Insufficient funds". Withdrawing 70 brings the balance to 0. The final `balance` confirms 0.

Your task

Implement the skeleton in the editor below so the commands produce the output shown in the example above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro