Reputation: 363
I have a simple if/elseif condition which I'm trying to convert it into a return statement with Ternay Operator for code redundancy but I have not been able to.
Any help would be appreciated, Thanks.
Here's my code snippet :
if (val.equals("a")||val.equals("s")){
return true;
}
else if (val.equals("b")||val.equals("t")) {
return false;
}
return true;
Could someone please suggest on how to proceed with return statement(Ternary Operator) for the above if/else-if ?
Upvotes: 0
Views: 297
Reputation: 1500175
There's no need for a conditional operator here. Your code will return true
so long as val
is neither b
nor t
:
return !(val.equals("b") || val.equals("t"));
or:
return !val.equals("b") && !val.equals("t");
The first condition around a
and s
is completely irrelevant, as the "default" return true
at the bottom already includes those cases.
EDIT: Now that you've changed the return type to int
, this would be reasonable to use with the conditional operator:
return val.equals("b") || val.equals("t") ? 0 : 1;
Upvotes: 6
Reputation: 16354
Try the follwing:
boolean b = ( val.equals("b") || val.equals("t") ) ? false : true;
return b;
Upvotes: -1
Reputation: 3059
return !(val.equals("b") || val.equals("t"));
This is the only condition that returns false - so you don't need to check the first condition.
Upvotes: 2
Reputation: 178421
return !(val.equals("b") || val.equals("t"))
The rest is redundant, val
cannot equal "a" or "s" and equal "b" or "t" at the same time, so you basically need to check if it equals "b" or "t", and return false
in this case, and true
in any other case.
Upvotes: 4