1

trying to find the smallest value in an array that isn't 0 as the array will almost always have empty values, i've got this far but stuck on how to stop it finding the 0's

 float smallest = Integer.MAX_VALUE; 
for(int x=0; x<priceArr.length;x++) {
    if(smallest > priceArr[x]) {
    smallest = priceArr[x];
    }
}
dovefromhell
  • 84
  • 1
  • 1
  • 12

2 Answers2

1

trying to find the smallest value in an array that isn't 0

The procedure is the same as finding the smallest from an array. On top of that, add a condition to check that the current search is not zero.

float smallest = Integer.MAX_VALUE; 
for(int x=0; x<priceArr.length; x++) {
    if(smallest < priceArr[x] && priceArr[x] != 0) {    //additional condition here
        smallest = priceArr[x];
    }
}

Note: The change from smallest > priceArr[x] to smallest < priceArr[x].

If your array size is at least 1, you can also set smallest as the first array element.

user3437460
  • 17,253
  • 15
  • 58
  • 106
0

In general case, to compare doubles with ==, you may consider error margin in their representation by using an epsilon value.
But this solution is not perfect either.
You can refer to this post.

Default float value is 0.0F.
So, you could so use this condition in the if statement :

float epsilon = 0.00000001F;

float currentValue = priceArr[x];
if (Math.abs(currentValue) < epsilon && smallest > currentValue ) {
   smallest = currentValue;
}

Note that using a local variable to store the priceArr[x] value reduces the duplication.

But beware as comparing floats by using an epsilon may give matching while the value is not really the 0 value.
For example this :

float[] array = new float[5];
array[0] = 0.000000001F;
float epsilon = 0.00000001F;

if (Math.abs(array[0]) < epsilon) {
    System.out.println("match");
}

will produce "match".

If your requirement is only ignoring elements of the array that were not explicitly valued, you should favor Float over float.
Float are by default null in an array and you could so test the nullity to ignore the element :

Float currentValue = priceArr[x];
if(currentValue != null && smallest > currentValue ) {
   smallest = currentValue;
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Given that the array seems to contain floats, using `!=` might be dangerous. Perhaps safer to use `>= 0.0`, assuming no negative values in the array. If there are then it gets more complex to check. As you say, integers would simplify things a lot. – rossum Oct 29 '17 at 15:56
  • Whoops! Thanks for the correction. `> 0.0` is correct. – rossum Oct 29 '17 at 16:01
  • @rossum I didn't see that float types were used. My bad. Using `>0` is a way but this means handling only positive values. It is not said in the question. – davidxxx Oct 29 '17 at 16:06