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

replace method

 
John Perry
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, i have a double[] array and i want to replace an item in the array. My method below takes a double from the user and checks if it exists, and when the element does exist, how do i find it's index and replace it with the value provided from the user?

scores[indexOfelement] = changeScore



Thanks.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have a couple of options, you could sort the array and call java.util.Arrays.binarySearch(score), if the return value is > -1 that is the index of your element. If the ordering of the array needs to be maintained, you can write a method that does a linear search of the array, and if it finds a particular element, have the method reurn the index of element, else have it return some value that cannot be an index, like -1.



 
John Perry
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That gave me a little insight but i'm still having trouble finding the exact index of what the user typed in.
If in the array i have the values:

1
2
3

and the user wants to replace the value 2 (which is at index 1) with let's say the value 5, how can that be done?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method you showed at the top returns true or false. Could you make it return the index instead?

if ( haystack[i] == needle ) return i;

From there you can use the rest of John's tips.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic