如何在数组中循环以找到最近的距离



我一直在想如何遍历一组邮政编码并找到离目标最近的邮政编码。邮政编码还包含它们的纬度和经度,用于计算到目标的距离。我需要弄清楚如何在存储最近距离的数组中循环,然后返回最近距离的邮政编码。任何帮助都会很好,因为我已经尽力了。

 * Finds and returns the zip code of a postal zone in the collection
 * whose centroid is closest to a given location. 
 * 
 * @param   target    the target location.
 * 
 * @return  returns zipCode of the postal zone whose centroid is closest;
 *          returns COLLECTION_EMPTY if no zones are in the collection.
 */
public String findClosestZone(Location target)
{
    int counter = 0;
    String closeZip = COLLECTION_EMPTY;
    double closestDistance = 100.0;
    for (int i = 0; i < this.zoneCount; i++)
    {
        if (this.zones[i].getZoneLocation()
            .calcDistance(target) < closestDistance)
        {
            closeZip = this.zones[i].getZoneZipCode();
            closestDistance = this.zones[i]
            .getZoneLocation().calcDistance(target);
            counter++;
            return closeZip;
        }
    }
    return closeZip;
}    

根据文档:

A method returns to the code that invoked it when it
1. completes all the statements in the method,
2. reaches a return statement, or
3. throws an exception,
whichever occurs first.

这意味着您的代码在第一次迭代之后就完成了它的工作。据我所知,你想在一系列区域中找到最接近的一个。我想您不需要循环内的return。请评论或删除。

public String findClosestZone(Location target)
    {
        int counter = 0;
        String closeZip = COLLECTION_EMPTY;
        double closestDistance = 100.0;
        for (int i = 0; i < this.zoneCount; i++)
        {
            if (this.zones[i].getZoneLocation().calcDistance(target) < closestDistance)
            {
                closeZip = this.zones[i].getZoneZipCode();
                closestDistance = this.zones[i].getZoneLocation().calcDistance(target);
                counter++;
                // return closeZip;
            }
        }
        return closeZip;
    }

最新更新