• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

replace method

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic