Alex
Alex

Reputation: 970

Check two conditions with two different outcomes (ternary operators)

I created a variable,

newval1 = lb + (ub - lb)*rnd.nextDouble();

which has to lie between two values, bounds[0] and bounds[1]. Currently I implemented this check in two lines with ternary operators:

            newval1 = ((newval1<bounds[0]) ? bounds[0] : newval1);
            newval1 = ((newval1>bounds[1]) ? bounds[1] : newval1);

I've no doubt there is a more efficient way of comparing newval1 to these bounds, preferable in 1 line. Any suggestions?

Upvotes: 1

Views: 81

Answers (1)

Alex Salauyou
Alex Salauyou

Reputation: 14338

val = Math.min(bounds[1], Math.max(bounds[0], val));

Upvotes: 8

Related Questions