-3

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

 * 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;
}    
4

1 回答 1

2

根据文档

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;
    }
于 2013-07-20T20:47:14.297 回答