This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes replace method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "replace method" Watch "replace method" New topic

replace method

John Perry

Joined: Oct 21, 2006
Posts: 5
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

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
John Perry

Joined: Oct 21, 2006
Posts: 5
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:


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

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: replace method
jQuery in Action, 3rd edition