内容要求:
按照面向对象方法,使用Java编写应用程序,实现:
在给定的一组二维坐标上点的集合中,找出距离最近的2个点,输出这2个点的坐标及距离。
从键盘输入集合中点的个数n,然后依次输入每个点的横、纵坐标。
输出2个点的坐标及距离。
运行示例:
分析:思路很简单,以一个点类对象数组存储所有的点,遍历循环所有点,求两两间距离,距离更小则更新记录最终结果的参数,最后输出。
代码片段如下:
public class Point {//创建一个点类
double x;//横纵坐标
double y;
public void init(double a,double b){//定义方法
this.x=a;
this.y=b;
}
public double getDistancePow(Point a){//求这一点到点a距离的方法
double distancePow;
distancePow=(a.x-this.x)*(a.x-this.x)+(a.y-this.y)*(a.y-this.y);
return distancePow;
}
}
import java.util.Scanner;
public class PointTest {
public static void main(String[] args) {
int pointNum;//输入点的个数
Scanner sc=new Scanner(System.in);
System.out.print("输入二维坐标系中点的个数:");
pointNum=sc.nextInt();
Point[] a=new Point[pointNum+1];//构造点的对象数组并赋值
System.out.println("输入"+pointNum+"个点的横坐标和纵坐标:");
for(int i=1;i<=pointNum;i++){
a[i]=new Point();
double a_sc,b_sc;
a_sc=sc.nextDouble();
b_sc=sc.nextDouble();
a[i].init(a_sc,b_sc);
}
double x1,x2,y1,y2,distancePow,temp;//用来记录最终结果的参数,初始化为第一个点和第二个点
distancePow=a[1].getDistancePow(a[2]);
x1=a[1].x;
x2=a[2].x;
y1=a[1].y;
y2=a[2].y;
for(int i=1;i<=pointNum;i++)//循环遍历所有点,求每两点间的距离
for(int j=i+1;j<=pointNum;j++){
temp=a[i].getDistancePow(a[j]);
if(distancePow>temp){
distancePow=temp;
x1=a[i].x;
x2=a[j].x;
y1=a[i].y;
y2=a[j].y;
}
}
System.out.printf("距离最近的两个点是(%.1f,%.1f)和(%.1f,%.1f),距离是%.2f",x1,y1,x2,y2,Math.sqrt(distancePow));//输出结果
}
}