Check data from users and report each problem with its own message, using exceptions.
What to build
A program that checks a list of ages.
Requirements
- Write a function that turns a text into an age or throws an
InvalidArgumentException:not a numberif the text is not made only of digits, andout of rangeif the number is above 120. - Read n, then n lines. For each print
valid: AGEorinvalid: REASON.
Input
Line 1: n. Then n lines of text (a line may be empty).
Output
n lines.
Constraints
1 ≤ n ≤ 30; each line has at most 20 characters.
Example
Input:
4
25
abc
150
-5
Output:
valid: 25
invalid: not a number
invalid: out of range
invalid: not a number
Why it works
The function reports a problem by throwing, and the loop decides how to show it, so the two jobs stay apart.
Examples
Example 1 · Input
4 25 abc 150 -5
Expected output
valid: 25 invalid: not a number invalid: out of range invalid: not a number
Example 2 · Input
2 0 120
Expected output
valid: 0 valid: 120
Hints
Hint 1
ctype_digit($text) is true only when the text is made of digits (and not empty).
Hint 2
Throw an InvalidArgumentException with the reason, and catch it in the loop.
Solution
Show one correct solution (try it yourself first)
<?php
function parseAge(string $text): int
{
if (!ctype_digit($text)) {
throw new InvalidArgumentException("not a number");
}
$age = (int) $text;
if ($age > 120) {
throw new InvalidArgumentException("out of range");
}
return $age;
}
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
$text = trim(fgets(STDIN));
try {
$age = parseAge($text);
echo "valid: $age\n";
} catch (InvalidArgumentException $e) {
echo "invalid: ", $e->getMessage(), "\n";
}
}