"Dave" <bigdavepotnoodle*SPAM*hotmail.com> wrote in message
news:3f***********************@news.dial.pipex.com ...
I am farly new to java and am interested in how to cover a 'range'.
ie. if variable != [1..6]
// 1.
if (variable >= 1 && variable <= 6)
{
// Do in-range stuff ...
...
}
// 2. [For numeric, integer-based primitive types ('char' too) only]
switch (variable)
{
case 1: case 2: case 3:
case 4: case 5: case 6:
// Do in-range stuff ...
break;
...
}
// 3. Use 'Set' collection
// a) Previously set up
Set s = new HashSet();
s.add(new Integer(1));
...
s.add(new Integer(6));
...
// b) Perform pseudo 'range' test [actually a membership test
// but it serves the required purpose]
if (s.contains(new Integer(variable)))
{
// Do in-range stuff ...
...
}
// 4. Iterate through a range [e.g. array or collection]
// testing for element membership ...
int[] array = new int[100];
array[1] = 1;
array[2] = 2;
array[3] = 3;
array[4] = 4;
array[5] = 5;
array[6] = 6;
int variable = 5;
boolean found = false;
for (int i = 0; i < array.length && !found; ++i)
found = (array[i] == variable);
if (found)
{
// Do in-range stuff ...
...
}
// 5. Use 'BitSet'
BitSet bs = new BitSet(100); // Range of 0 .. 99
bs.clear(0);
bs.set(1, 6); // Set values 1..6
bs.clear(7, 99);
if (bs.get(variable))
{
// Do in-range stuff ...
...
}
This is similar to doing:
boolean[] array = new boolean[100];
array[1] = true;
array[2] = true;
array[3] = true;
array[4] = true;
array[5] = true;
array[6] = true;
...
int variable = 5;
boolean found = array[variable];
if (found)
{
// Do in-range stuff ...
...
}
The third, fourth, and fifth examples are probably not what you want but are
shown for sake of illustration. If you try to 'think outside the square',
*much* is possible using Java :) !
I hope this helps.
Anthony Borla