Question

I know that ternary operator is used of doing a variable assignment after a evaluating a logical condition.

So:

String s = (logicalVariable) ? "Hello" : "Bye, bye";

or,

int x = (5<3) ? 10 : 100;

would be usage examples, right?

But what if Idon't really want to do a variable assignment but to set a sentence or even a piece of code, for example:

if (inventario.containsKey(item))
        return inventario.get(item);
    else return Integer.MIN_VALUE;

Can these lines be writen in a one line expression, probably by using the ternary operator?

Was it helpful?

Solution

This should work:

return inventario.containsKey(item)? inventario.get(item); Integer.MIN_VALUE;

The first part just need to evaluate to a boolean

OTHER TIPS

return inventario.containsKey(item) ?  inventario.get(item) : Integer.MIN_VALUE;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top