Your first class: data and the actions on it together.
What to build
A program with a Counter class that runs commands.
Requirements
- Write a class
Counterthat starts at 0, with methodsinc(),dec()(never below 0),reset()andvalue(). - Read lines until the input ends. For
inc,decandresetchange the counter; forshowprint its value.
Input
Any number of lines, each one of: inc, dec, reset, show.
Output
One line for each show.
Constraints
At most 100 lines.
Example
Input:
inc
inc
show
dec
show
Output:
2
1
Why it works
The value is private, so only the methods can change it, and dec() protects the rule that it never goes below 0.
Examples
Example 1 · Input
inc inc show dec show
Expected output
2 1
Example 2 · Input
dec show
Expected output
0
Hints
Hint 1
Keep the value in a private property and change it only through methods.
Hint 2
In dec(), do nothing when the value is already 0.
Solution
Show one correct solution (try it yourself first)
<?php
class Counter
{
private int $count = 0;
public function inc(): void
{
$this->count++;
}
public function dec(): void
{
if ($this->count > 0) {
$this->count--;
}
}
public function reset(): void
{
$this->count = 0;
}
public function value(): int
{
return $this->count;
}
}
$counter = new Counter();
while (($line = fgets(STDIN)) !== false) {
$cmd = trim($line);
if ($cmd === "inc") {
$counter->inc();
} elseif ($cmd === "dec") {
$counter->dec();
} elseif ($cmd === "reset") {
$counter->reset();
} elseif ($cmd === "show") {
echo $counter->value(), "\n";
}
}