Java: How to tell an if statement to ignore multiple values without writing them all out? (grouping?
6 replies, posted
I want to do an if statement but I need to write this for example "if (variable != 24 && != 36 && != 54..." and continuing on with a lot more. However I don't want a huge line of code. Is there anyway to group these numbers so I can write "if (variable != groupednumbers)"
Thanks in advance
Use an array and arrays.contains
I suppose you could have an ArrayList of Integers and simply call
[code]
if (myList.contains(someNumber))
{
//something
}
[/code]
Of course, there's probably a better method.
[editline]14th March 2012[/editline]
Ninja'd
If it's a really huge list and they're all sorted like your example you could do a binary search.
Yeah just call Arrays.sort after you store everything in the array.
Got bored and just wrote the code for you.
[code]
private static final int[] list = new int[]{24, 36, 56, 64, 75, 101, 205, 543, 939, 1024, 1292, 4834, 9593, 10020};
public static void main(String[] args)
{
System.out.println(contains(64));
}
private static boolean contains(int n)
{
int a = -1;
int b = list.length;
while (true)
{
int i = (a + b) / 2;
int ni = list[i];
if (n > ni) a = i;
else if (n < ni) b = i;
else return true;
if (Math.abs(a-b) <= 1) return false;
}
}
[/code]
[QUOTE=Smashmaster;35140936]Got bored and just wrote the code for you.
[code]
private static final int[] list = new int[]{24, 36, 56, 64, 75, 101, 205, 543, 939, 1024, 1292, 4834, 9593, 10020};
public static void main(String[] args)
{
System.out.println(contains(64));
}
private static boolean contains(int n)
{
int a = -1;
int b = list.length;
while (true)
{
int i = (a + b) / 2;
int ni = list[i];
if (n > ni) a = i;
else if (n < ni) b = i;
else return true;
if (Math.abs(a-b) <= 1) return false;
}
}
[/code][/QUOTE]
You don't even have to bother doing that, there is a binarySearch method in the Arrays class.
[url]http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html[/url]
Sorry, you need to Log In to post a reply to this thread.