For-each loop
My Java is somewhat rusty but I think you could use a for-each
loop to write something like :
For-each loop
for (TargetScope s: TargetScope.values())
{
double distance = Math.abs(s.getPercent() - alpha);
if (distance < delta) {
delta = distance;
scope = s;
}
}
Code organisation
To be honest with you, I have no idea what your code is supposed to be doing. However, wouldn't it make sense to define a method getInterfaceScopeByTime()
taking the time you want to approximate as an argument instead of using the attribute time? It would make things somewhat easier to test/understand and you can always call the method with this.time
if required.
Algorithm
From an algorithm point of view, depending on the number of times you plan to do this, you might find interesting to perform some preprocessing whose cost will be amortised to achieve better average performances. Among the different options. For instance, you can sort the values : if at a given step, the computed distance is bigger than the minimal distance, it means that you are getting away from the closest value and you can stop iterating. Otherwise, you can use a binary search to find the closest value.