Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Java: Math condition

Is there a simple way to do this

if (1 < x && x < 3) { .... }

I want something like this:

if (1 < x < 3) { .... }

I know that the code above is wrong but....

Thanks

Upvotes: 1

Views: 1537

Answers (6)

Pete Kirkham
Pete Kirkham

Reputation: 49311

Assuming you're talking about integers:

if ( x == 2 ) { .... }

There's quite a few little bits of Java which come from it being a better C++ - in C or C++, there's an automatic conversion between boolean values and integers, so in C++:

int x = 5;

std::cout << std::boolalpha;

std::cout << ( 1 < x < 3 ) << std::endl;
std::cout << ( ( 1 < x ) < 3 ) << std::endl;

will print "true" twice, as ( 1 < x ) evaluates as 1 and 1 is less than 3. Java concentrates on fixing this ambiguity with parsing two binary operators by making boolean and integer types non-convertible so you have to join them with another operator; other languages don't try and fix C++ but have more complicated parsing rules so that _ < _ < _ is a ternary operator which does the right thing.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500275

You've got the simplest form in terms of straight Java syntax. You could introduce a method if you wanted:

public static boolean isBetween(int x, int min, int max) {
    return min < x && x < max;
}

then call it with:

if (isBetween(x, 1, 3))

but I don't think that's really any clearer - and it means there's more possibility of putting the arguments in the wrong order. The Range class suggested in another answer would alleviate that concern, but at the price of adding even more clutter...

Upvotes: 3

David Crawshaw
David Crawshaw

Reputation: 10577

In terms of efficiency, (1 < x && x < 3) is as good as you will get. To put an integer in a range, you need to do two comparisons.

If you want to make your code more readable and you have a lot of these ranges, you may want to consider creating an Interval class with a contains() function.

Upvotes: 3

Andrzej Doyle
Andrzej Doyle

Reputation: 103787

Not using the language builtins; you'd need to go with your first answer.

Several libraries will let you do something like the following:

Range range = new ExclusiveRange(1,3);
if (range.contains(x)) { ... }

Upvotes: 3

Noldorin
Noldorin

Reputation: 147270

Thate statement using && is the simplest you can get. Java, nor any other C-style language I know, has support for chained inequalities.

Upvotes: 1

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

Unfortunately, you can't do that in Java. You can, however, create a class, say MathUtils, with a isBetween method, like so:

public static boolean isBetween(int n, int begin, int end) {
  return n > begin && n < end;
}

Then, you could use (assuming you import static):

if (isBetween(x, 1, 3)) {
  // ...
}

But this would only be helpful if you have many range conditions.

Upvotes: 6

Related Questions