如何遍历数组以找到最近的距离?

时间:2013-07-20 20:26:09

标签: java loops distance

我试图弄清楚如何遍历邮政编码数组并找到最接近目标的邮政编码。邮政编码还包含其纬度和经度,用于计算到目标的距离。我需要搞清楚如何循环存储最近距离的数组,然后返回最接近的邮政编码。任何帮助都会很棒,因为我已经尝试过所有我能想到的东西。

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

1 个答案:

答案 0 :(得分:2)

根据doc

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