Java — Validating input with OptionalInt
Java OptionalInt can represent either an accepted seat number or an empty result. Check conversion and range before returning a value to the caller.
A simple example
Turn text into a number
- Start with "2"
- Do this Read an integer, add 1
- Result 3
class Main {
public static void main(String[] args) throws Exception {
int n = Integer.parseInt("2");
System.out.println(n + 1);
}
}
3
Validate a seat number
OptionalInt communicates either a valid primitive int or an empty result. Decimal text can still exceed the int range, so the parser handles NumberFormatException before checking the seat range.
A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.
Run the example
Java 17 or later. Run these commands from the directory containing the example.
java Main.java
import java.util.List;
import java.util.OptionalInt;
class Main {
static OptionalInt seatNumber(String text) {
if (!text.matches("[0-9]+")) return OptionalInt.empty();
try {
int n = Integer.parseInt(text);
return n >= 1 && n <= 8 ? OptionalInt.of(n) : OptionalInt.empty();
} catch (NumberFormatException overflow) {
return OptionalInt.empty();
}
}
public static void main(String[] args) {
for (String text : List.of("3", "0", "x")) {
OptionalInt seat = seatNumber(text);
System.out.println(seat.isPresent() ? Integer.toString(seat.getAsInt()) : "invalid");
}
}
}
3 invalid invalid
Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.
Try it yourself
Predict the results for 8, 9, and an empty string.
Check your answer
Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.