# Defining numerical set in java

• 05-04-2011, 04:24 AM
veronique
Defining numerical set in java
Hi,

I'd like to declare a numerical set like this [2, 10] which basically reads all numbers from 2 and 10. Basically I want to avoid using this || in if statement:
if(i > 2 || i < 10) ... is there a way to do something like (if i belongs to set [2, 10])?

thanks,
ruslan
• 05-04-2011, 04:32 AM
Artel
What exactly are you trying to do? Are you trying to find whether or not a number is between two values?
• 05-04-2011, 04:33 AM
veronique
exactly ... just trying to see if there is a better way

thanks
• 05-04-2011, 05:11 AM
Artel
If you're trying to find a number between, you'll need to use the and operator:
I guess since you're using brackets you want it to be inclusive? (greater than or equals, less than or equals)
Code:

`i >= 2 && i <= 10`
You can use a helper method:
Code:

```public boolean isIncluded(int low, int high, int num) {   return num >= low && num <= high;   //if it is greater than/equal to low and less than/equal to high, it will return true. If not, it will return false. }```
Then, when you want to find if a number is in between the two values, you call the method:

Code:

```if(isIncluded(2, 10, i)) {   //code if the number belongs in the set } else {   //if the number doesn't fall into range }```
• 05-04-2011, 05:42 AM
veronique
yes I meant AND operator not OR.

I'm looking for different structure if one exists ... basically JAVA representation of [2, 3] which could be statically declared right off the bat without using helper methods like you provided. I think python has that, but I could not find anything like that in JAVA.
• 05-04-2011, 06:09 AM
DarrylBurke
You couldn't find it because it doesn't exist. If you have frequent need for this, go with the helper method.

db
• 05-04-2011, 07:24 AM
ranjiths
You can use a nested loops if you would like to avoid using &&
Following will be the code snippet:

int i=0;
while(i<=10)
{
if(i>=2)
System.out.println(i); //or any other statements that use the generated number, for example a method call that passes this number
i++;
}
}

- Ranjith
• 05-04-2011, 08:05 AM
JosAH
Maybe a BitSet can be of any help here ... (read the API documentation for that class).

kind regards,

Jos
• 05-04-2011, 08:08 AM
DarrylBurke
Quote:

Originally Posted by ranjiths
You can use a nested loops if you would like to avoid using &&

That's just silly. Learn Java and programming instead of polluting these forums with your oversized signature.