import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ShortDistance {
static class Point{
private double x;
private double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* 计算点p 到该点的距离
* @param p
* @return
*/
public double distance(Point p){
return Math.sqrt(Math.pow(p.x - this.x ,2) + Math.pow(p.y - this.y, 2));
}
public double findShortDistance(List<Point> points){
double min = 0;
Point result = null;
for(Point p : points){
if(p == this || p.equals(this))
continue;
double distance = distance(p);
if(min == 0 || (min != 0 && distance < min)){
min = distance;
result = p;
}
}
System.out.println("距离" + this + "最近的点是:" + result + "距离为:" + min);
return min;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Point))
return false;
Point p = (Point)obj;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
int result = 17;
long dx = Double.doubleToLongBits(x);
result += (dx ^ (dx >>> 32));
long dy = Double.doubleToLongBits(y);
result += (dy ^ (dy >>> 32));
return result;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
public static void main(String[] args) {
System.out.println("输入点集合:(x1,y2) (x2,y2) (x3,y3) ... (xn,yn)");
//(3,5) (3,12) (4,9) (2,8) (5,11)
Scanner scanner = new Scanner(System.in);
String content = scanner.nextLine();
scanner.close();
List<Point> points = dealPointContent(content);
if(points.size() > 0){
for(Point point : points){
point.findShortDistance(points);
}
}
}
public static List<Point> dealPointContent(String content){
ArrayList<Point> points = new ArrayList<Point>();
String[] items = content.split(" ");
for(String item : items){
item = item.replaceAll("[()]", "");
String[] ps = item.split(",");
if(ps.length != 2)
continue;
Point point = new Point(Double.parseDouble(ps[0].trim()),Double.parseDouble(ps[1].trim()));
points.add(point);
}
return points;
}
}
本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。