• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the nearst value in an array  RSS feed

 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an app where a user keys a decimal value, and the fraction
for that value displays underneath. It works okay. Now I want to automatically find the closest matching decimal value in a fraction array if they happen to key the wrong one, and automatically change it for them.
I have been trying to think of a way to do this, but can't really come up with anything good.
Does anyone have any ideas on how to get the closest matching value?
Thanks for any help!
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming that the fraction array is called "fraction", and the user-supplied value is "userVal", then here's some pseudo-code for you ...

When you get through your loop, "ndx" will be the index into "fraction" of the closest match. It should be pretty easy to translate this into Java. NOTE: this assumes that your "fraction" array is typed as double[]. However even if that isn't the case, this should provide a framework for you.
 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank for the help. I converted to java code and it works beautifully!!
Thanks again!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!