开发者

Elegant way to code if (10 < x < 20)

开发者 https://www.devze.com 2022-12-27 03:25 出处:网络
Is there an elegant way in Java to code: if (10 < x < 20) { ... } i.e. \"if开发者_C百科 x is between 10 and 20\"

Is there an elegant way in Java to code:

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

i.e. "if开发者_C百科 x is between 10 and 20"

rather than having to write

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

Thanks!


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

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


Kenny nailed it in the comments.

if (10 < x && x < 20)

You want to keep them either both less-than or both greater-than; reversing the direction of the comparison makes for a confusing bit of logic when you're trying to read quickly.


No but you can re-arrange it to make it better, or write a wrapper if it irks you:

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

Or, as Carl says:

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

Though personally, I don't see the point. It's a useless abstraction. The bare boolean statement is perfectly obvious.

Though, now that I think about it, and in light of Carl's comment below, there are times when a Range is a perfectly valid and useful abstraction (e.g. when dealing with Feeds). So, depending on the semantics of x, maybe you do want an abstraction.


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

   //...

   }
  }

OR

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

   //...

   }
  }


The only thing you can do is loose the extra parenthesis since the && has a lower precedence than > and <:

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

Other than that: there's no shorter way.


The FASTEST way is a switch.


EDIT:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消