An elegant way to code if (10 <x <20)

Is there an elegant way in Java:

if (10 < x < 20) {
   ...
}

      

i.e. "if x is between 10 and 20"

instead of writing

if ((x > 10) && (x < 20)) {
   ...
}

      

Thank!

+2


source to share


6 answers


No. The operator <

always compares two elements and results in a boolean value, so you cannot chain them "elegantly". You could do this though:



if (10 < x && x < 20)
{
    ...
}

      

+14


source


Kenny nailed it in the comments.

if (10 < x && x < 20)

      



You want to keep them either as smaller or both large; changing the direction of the comparison leads to a confusing bit of logic when you try to read quickly.

+5


source


No, but you can rearrange it to make it better, or write a wrapper if it annoys you:

if (InRange(x, 10, 20)) { ... }

      

Or, as Karl says:

if (new Range(10, 20).contains(x)) { ... }

      

Although personally I don't see the point. This is a useless abstraction. The bare boolean operator is quite obvious.

Although, now that I think about it, and in light of Karl's comment below, there are times when Range is a perfectly valid and useful abstraction (for example, when working with Feeds). So, depending on the semantics x

, you might want an abstraction.

+5


source


  if(x < 20)
  {
   if(x > 10)
   {

   //...

   }
  }

      

OR

 if(x > 10)
  {
   if(x < 20)
   {

   //...

   }
  }

      

+4


source


The only thing you can do is free the extra parenthesis as it &&

has a lower precedence than >

and <

:

if (x > 10 && x < 20) {
   ...
}

      

Other than that: there is no shortcut.

+1


source


The fastest way is with a switch.


EDIT:

switch(x) {
  case 10:
  case 11:
  case 12:
  case 13:
  ...
  case 19: System.out.println("yes");
}

      

compiled into a jump table, not a long series of ifs.

0


source







All Articles