Click here to Skip to main content
15,901,426 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In this method i am returning the nearest assistant based on the distance between the locations. However, the way this works i could end up with a negative number for the distance if the two operands of the subtraction happen to be one way around rather than the other. And i need the positive equivalent, but im not sure how to code this.

What I have tried:

Java
<pre>public Assistant findNearestAvailable(int location)
    {
        Iterator<Assistant> it = assistants.iterator();
        Assistant nearestAssistant = null;
        int nearestDistance = Integer.MAX_VALUE;
        int nearestID = Integer.MAX_VALUE;

        while(it.hasNext()) {
            Assistant assistant = it.next();
            if(assistant.isAvailable()) {
                int distance = location - assistant.getLocation();
                if(distance < nearestDistance){
                    nearestDistance = distance;
                    nearestAssistant = assistant;
                }
                else if(){
                    
                }

                else if(distance == nearestDistance){
                    if(identity < nearestID){
                        nearestID = identity;
                        nearestAssistant = assistant;
                    }
                }
            }
        }
        return nearestAssistant;
    }
Posted
Updated 21-Nov-22 7:39am
v2

Look at the Java - abs() Method[^]
 
Share this answer
 
Comments
Freddie Francis 21-Nov-22 12:29pm    
what am i doing wrong here. It tells me that theres no suitable method found for abs:



if(distance < nearestDistance){
nearestDistance = distance(Math.abs());
nearestAssistant = assistant;
}
OriginalGriff 21-Nov-22 12:52pm    
I don't know, I don't have access to your code.

But ... did you import java.lang.Math
Replace
Quote:
int distance = location - assistant.getLocation();
with
Java
int distance = Math.abs(location - assistant.getLocation());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900