Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing a variable to an array

 
Terence hiu
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Android Chrome Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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))
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic