This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Comparing a variable to an array

Terence hiu
Ranch Hand
Posts: 36
Hi guys, how would i compare a single int variable to an arrray?
i would like to check wether an int variable has the same value in the array and then return something

Jeff Verdegan
Bartender
Posts: 6109
6
You mean you want to see if one of the elements in the array has the same value as the int? Comparing the int 123 to the array [2, 4, 6, ...] doesn't make much sense.

Assuming you're talking about seeing whether that value is present in one element of the array, you can either A) iterate over the array, comparing each element to the value in question until you find a match or hit the end of the array, or B) if the array is sorted, use Arrays.binarySearch() (http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int[],%20int))

Aj Prieto
Ranch Hand
Posts: 75
What do you want it to do?

You want to have a value and check to see if an array contains the same value?

Terence hiu
Ranch Hand
Posts: 36
Thankyou, that really helped me

Jeff Verdegan wrote:You mean you want to see if one of the elements in the array has the same value as the int? Comparing the int 123 to the array [2, 4, 6, ...] doesn't make much sense.

Assuming you're talking about seeing whether that value is present in one element of the array, you can either A) iterate over the array, comparing each element to the value in question until you find a match or hit the end of the array, or B) if the array is sorted, use Arrays.binarySearch() (http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int[],%20int))