aspose file tools*
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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "replace method" Watch "replace method" New topic
Author

replace method

John Perry
Greenhorn

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



Thanks.
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
Greenhorn

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:

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

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: http://aspose.com/file-tools
 
subject: replace method
 
Similar Threads
Array returning last value entered
How to return value back to main?
more problems calling methods
How should I split up this big method? Still need help please!
User input, change into an Array, send to a new method, then output results