Java如何读取文本文件中的城市坐标并计算距离最近的两个城市
实现方案
1. 扩展Point类
原有Point类缺少城市名称存储属性,先补充功能:
static class Point { int x, y; String name; public Point(int x, int y, String name) { this.x = x; this.y = y; this.name = name; } // 计算两点距离的平方,避免提前开根号损耗性能、损失精度 public long distanceSq(Point other) { long dx = this.x - other.x; long dy = this.y - other.y; return dx*dx + dy*dy; } // 计算实际距离,输出时使用 public double distance(Point other) { return Math.sqrt(distanceSq(other)); } }
2. 读取文本文件解析数据
使用带缓冲的BufferedReader读取文件,IO效率更高,逐行解析坐标和城市名存入列表:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ClosestCity { public static void main(String[] args) { String filePath = "你的文件路径.txt"; // 替换为实际文件路径 List<Point> cities = new ArrayList<>(); // 读取文件解析数据 try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { // 按任意空白符拆分每行,过滤掉多余空格 String[] parts = line.trim().split("\\s+"); if (parts.length < 3) continue; // 跳过格式错误的行 int x = Integer.parseInt(parts[0]); int y = Integer.parseInt(parts[1]); String name = parts[2]; cities.add(new Point(x, y, name)); } } catch (IOException e) { e.printStackTrace(); return; } catch (NumberFormatException e) { System.out.println("坐标格式错误:" + e.getMessage()); return; } if (cities.size() < 2) { System.out.println("城市数量不足2个,无法计算"); return; } // 查找最近的两个城市 Point cityA = cities.get(0); Point cityB = cities.get(1); long minDistSq = cityA.distanceSq(cityB); // 暴力枚举所有点对,数据量在10000以内时性能足够 for (int i = 0; i < cities.size(); i++) { for (int j = i + 1; j < cities.size(); j++) { long currentSq = cities.get(i).distanceSq(cities.get(j)); if (currentSq < minDistSq) { minDistSq = currentSq; cityA = cities.get(i); cityB = cities.get(j); } } } // 按要求格式输出 double dist = Math.sqrt(minDistSq); System.out.printf("%s and %s are closest with a distance of %.3f%n", cityA.name, cityB.name, dist); } }
3. 大数据量优化
如果城市数量超过10000个,暴力法O(n²)的时间复杂度会性能不足,可以替换为分治算法实现的最近点对查找,时间复杂度可以降到O(nlogn)。
内容的提问来源于stack exchange,提问作者user16818633
相关产品推荐
相关产品推荐

