This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Comparing a variable to an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing a variable to an array" Watch "Comparing a variable to an array" New topic
Author

Comparing a variable to an array

Terence hiu
Ranch Hand

Joined: Oct 21, 2012
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

Joined: Jan 03, 2004
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

Joined: Sep 28, 2012
Posts: 72

What do you want it to do?

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


Da mihi sis bubulae frustum assae, solana tuberosa in modo Gallico fricta ac quassum lactatum coagulatum crassum.
Terence hiu
Ranch Hand

Joined: Oct 21, 2012
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))
 
jQuery in Action, 2nd edition
 
subject: Comparing a variable to an array
 
Similar Threads
array.length question
Differnce between array declaration
Local Array
Array of Objects
Explain this code about Arrays