Reputation: 11
if(input.charAt(i) == '0' || input.charAt(i) == '1' || input.charAt(i) == '2') {
}
Is there a way to condense this if condition, or no?
Upvotes: 0
Views: 57
Reputation: 17880
You can make it shorter by assigning the character lookup result in a variable (but still three equality checks).
char c = input.charAt(i);
if(c == '0' || c == '1' || c == '2') {
}
You can look at the other answers like creating a Set/Array and doing the contains check if the number of equality checks will increase in the future. IMO, three checks should be fine to be written as is.
Upvotes: 0
Reputation: 59274
Maybe a little more readable (in java 9+)
if (Set.of('0', '1', '2').contains(input.charAt(i))) {
}
Upvotes: 2
Reputation: 201439
You could check if the character matches any index in a common String
. Like,
if ("012".indexOf(input.charAt(i)) > -1) {
}
Upvotes: 3