# Thread: Defining numerical set in java

1. Member
Join Date
Apr 2011
Posts
22
Rep Power
0

## 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

2. Member
Join Date
May 2011
Posts
4
Rep Power
0
What exactly are you trying to do? Are you trying to find whether or not a number is between two values?

3. Member
Join Date
Apr 2011
Posts
22
Rep Power
0
exactly ... just trying to see if there is a better way

thanks

4. Member
Join Date
May 2011
Posts
4
Rep Power
0
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)
Java Code:
`i >= 2 && i <= 10`
You can use a helper method:
Java 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:

Java Code:
```if(isIncluded(2, 10, i))
{
//code if the number belongs in the set
}
else
{
//if the number doesn't fall into range
}```

5. Member
Join Date
Apr 2011
Posts
22
Rep Power
0
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.

6. You couldn't find it because it doesn't exist. If you have frequent need for this, go with the helper method.

db

7. 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
Last edited by ranjiths; 05-07-2011 at 03:11 PM. Reason: error

8. Maybe a BitSet can be of any help here ... (read the API documentation for that class).

kind regards,

Jos

9. 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.

db

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•