I don’t think your for loop is doing what you want it to do. Like, at all.
temps[i] = in.nextInt(); // This is sensible enough
closest = Math.abs(temps[0]); // Every time your loop runs, the closest value to 0 is... the absolute value of the first int in the array?
//System.err.println(temps[i]);
if (closest > 0) // This is only false if closest is 0
{
if (closest > i) // This makes the outer if redundant, since i >= 0. It's also not clear what the point of this condition even is
{
closest = i; // Here's the big one: you're setting closest to your iterator, the index of the current number in the array instead of the number itself.
}
}
else if (closest < 0) // This is never true, since absolute values are always >=0
{
if (closest < i)
{
closest = i;
}
}
}
Go through your code, one line at a time, keeping track of the values of each variable, and you’ll be able to find both where the numbers you get are coming from and if what you’re doing makes any sense.
It looks like you’ve got most of the right pieces somewhere in there, but they’re not being put together properly. When you’re revising your algorithm, don’t lose sight of your objective: you want to find the number in your list with the least absolute value. You can do this by checking that the absolute value of your next number is less than the current least value.
solved Where is my program pulling random numbers from?