Read a quantity someone typed
A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.
- Whitespace around the number is fine and is ignored.
- Only digits are allowed — no sign, no decimal point, no spaces inside.
- The value must be between 1 and 999.
- Anything else gives -1.
validQuantity(text: string) → int
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int validQuantity(String text) {
}
Worked examples
| Call | Result |
|---|---|
validQuantity("5") | 5 |
validQuantity(" 12 ") | 12 |
validQuantity("999") | 999 |
validQuantity("0") | -1 |
Hint
Trim, reject an empty result, then check every remaining character before you convert.
Reference solution in Java
int validQuantity(String text) {
String t = text.trim();
if (t.isEmpty()) return -1;
for (char c : t.toCharArray()) if (c < '0' || c > '9') return -1;
long n = Long.parseLong(t);
return (n >= 1 && n <= 999) ? (int) n : -1;
}