java定义point类,每个点包含(x,y)坐标,利用随机函数产生十个点的(x,y)值,将创建的point实例存入一个数组中,按与原点(0,0)的距离由小到大输出所有的点及到原点的距离
时间: 2024-05-27 15:11:49 浏览: 16
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());
}
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)