Devon Devon - 1 year ago 91
Java Question

How to find a value in an array that is closest to a given number

I'm trying very hard to understand this concept (arrays), but I'm having so much trouble (it's my first computer science course.) Here is my code, with the problem commented at the top. I've tried to solve this problem, but I don't think my logic is correct because I'm not getting a desired answer.

// Generate an array of 50 random numbers between 1 to 100. Now, find the number in the array closest to 75 and output it using println().

int[] numbers = new int[50];
int targetNumber = 75;

for (int i = 0; i < numbers.length; i++){
numbers[i] = (int) random(1,100);

int closestSoFar = abs(numbers[i]-targetNumber);

if(closestSoFar > targetNumber){
closestSoFar = abs(numbers[i]-targetNumber);


Whereas I would be VERY grateful for the correct answer, I would LOVE to hear why it's the correct answer, and how going forward I can improve my logic so I can do it on my own in the future.

Answer Source

As requested I'll explain what I think the answer is and then some hints on how you could have found it.

Your logic is:

int closestSoFar = abs(numbers[i] - targetNumber);
if (closestSoFar > targetNumber) {

Now imagine the number is '76'. closestSoFar will become abs(76 - 75) which is 1. That's clearly not larger than 75.

So the logic error is simple: you are comparing a difference to an absolute number.

The resolution is that you really need to check if the current number numbers[i] is closer than closestSoFar. That can be done with:

if (abs(numbers[i] - targetNumber) < abs(closestSoFar - targetNumber)) {

Now, with respect to how you could have found it yourself, here are some tips:

  1. The first, and simplest, is to look at your code and run through a scenario in your head (in this case the number 76). Check as you go that the results are what you expect. That would have found it for you in this case.
  2. If that doesn't work (e.g. the logic is too complex to do in your head) then use an interactive debugger. Step through the logic examining variables and again checking that it is returning what you expect.
  3. If that still doesn't help then you are going to have to refactor your code to break it down into smaller pieces that you can independently verify. This is where unit testing is your friend. In this case you could create a method such as isClosestToTarget and have some unit tests that ensures it does what you expect before moving on to methods that use the already tested methods.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download