• Post Reply Bookmark Topic Watch Topic
  • New Topic

finding if an array contains a value  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is a challenge for you guys I couldn't solve it I even googled it but all the suggestions said to use imports that are not in the standards java SDK

anyway what I want to do is find if an array contains a value as you can see with my example once the value is not found the recursive call keeps going and checks past the end of the array giving an ArrayOutOfBounds Exception

I want to be able to find if an array contains a value that I don't to import frameworks not from the java SDK and also it would  preferable to use logic instead of Arrays.toList()

thanks heres what I have come up with so far
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also using recursion may I add
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
giving an ArrayOutOfBounds Exception

Please copy the full text of the error message and paste it here. It has important info about the error.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam Chalkley wrote:
anyway what I want to do is find if an array contains a value as you can see with my example once the value is not found the recursive call keeps going and checks past the end of the array giving an ArrayOutOfBounds Exception


Your range check is incorrect. Remember that array indexes are zero based, so trying to access the element, of the array length is not allowed. You need to confirm if the index is greater than or equal to the length.

Henry
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point Henry I should have used >=
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point Henry I should have used >=

worked fine after that
 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To find if an element exists within an array, you can do it a couple of simple ways on top of my head.

One is doing a linear search on a small array like the one provided, it won't take too long. However, assuming you had a dataset or an array millions of numbers. I would use a binary search. However, for a binary search to be effective, all numbers in the array must be sorted.
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys =)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!