Savings jar commands
A family keeps a savings jar and writes down every action. Model the jar as a class Jar with a private integer balance and three methods: add(int $amount) puts money in, take(int $amount) removes money but returns false without changing anything when the jar does not hold enough, and balance() reports the current amount. Then read a list of commands: add X, take X and show. A refused take prints Declined: X; show prints Balance: N; nothing else prints anything.
Input
The first line is N (1 to 1000). Each of the next N lines is add X, take X or show, where X is an integer from 1 to 1000000.
Output
One line for every show command and every refused take, in the order they happen.
Example 1
Input
3 add 50 take 20 show
Output
Balance: 30
50 in, 20 out, 30 left. add and a successful take print nothing.
Example 2
Input
5 add 30 take 100 show take 30 show
Output
Declined: 100 Balance: 30 Balance: 0
Taking 100 from 30 is refused and the balance is untouched. Taking exactly 30 empties the jar.
Constraints
- 1 <= N <= 1000
- 1 <= X <= 1000000
- The balance starts at 0
Hints
Hint 1 of 3
Inside a method, the object's own property is $this->balance.
Hint 2 of 3
take should compare before it subtracts: if the amount is larger than the balance, return false right away.
Hint 3 of 3
In the loop, $parts[0] is the command and $parts[1] (when present) is the amount; use if / elseif on the command and call the matching method.
Solution
Show a reference solution and explanation
<?php
class Jar
{
private int $balance = 0;
public function add(int $amount): void
{
$this->balance += $amount;
}
public function take(int $amount): bool
{
if ($amount > $this->balance) {
return false;
}
$this->balance -= $amount;
return true;
}
public function balance(): int
{
return $this->balance;
}
}
$jar = new Jar();
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
$parts = explode(' ', trim(fgets(STDIN)));
$command = $parts[0];
$amount = (int) ($parts[1] ?? 0);
if ($command === 'add') {
$jar->add($amount);
} elseif ($command === 'take') {
if (!$jar->take($amount)) {
echo "Declined: $amount\n";
}
} elseif ($command === 'show') {
echo "Balance: ", $jar->balance(), "\n";
}
}
Why it works
The class keeps the balance private so it can only change through methods that enforce the rule, which is the main reason to use a class here rather than a bare variable. take() returns a boolean instead of printing, so the class knows nothing about the command format or the output; the loop decides what to print. That separation is what makes the class reusable. $this->balance reads and writes the current object's property; declaring it as private int $balance = 0 (a typed property, PHP 7.4+) gives it a starting value and prevents a string from sneaking in. The command loop only splits the line and dispatches; the ?? 0 fallback covers show, which has no second word.