java定义point类,每个点包含(x,y)坐标,利用随机函数产生十个点的(x,y)值,将创建的point实例存入一个数组中,按与原点(0,0)的距离由小到大输出所有的点及到原点的距离
时间: 2024-05-27 14:11:49 浏览: 114
Java 编写Point类,构造方法,计算两个点之间的距离,键盘输入两个点,格式以“,”隔开,如:1,1即为(1,1)点。
5星 · 资源好评率100%
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double distanceToOrigin() {
return Math.sqrt(x * x + y * y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
Point[] points = new Point[10];
// 随机生成十个点
for (int i = 0; i < points.length; i++) {
int x = (int) (Math.random() * 100);
int y = (int) (Math.random() * 100);
points[i] = new Point(x, y);
}
// 按距离排序
Arrays.sort(points, new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
double d1 = p1.distanceToOrigin();
double d2 = p2.distanceToOrigin();
return Double.compare(d1, d2);
}
});
// 输出结果
for (Point point : points) {
System.out.println(point + " distance to origin: " + point.distanceToOrigin());
}
}
}
阅读全文