java定义Point类,每个点包含(x,y)坐标,利用随机函数产生10个点的(x,y)值,将创建的 Point实例存入一个数组中,按与原点(0,0)的距离由小到大的顺序输出所有的点及到原点的距离。
时间: 2024-05-14 11:14:53 浏览: 87
Java 编写Point类,构造方法,计算两个点之间的距离,键盘输入两个点,格式以“,”隔开,如:1,1即为(1,1)点。
5星 · 资源好评率100%
代码如下:
```java
import java.util.Arrays;
import java.util.Random;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distanceToOrigin() {
return Math.sqrt(x * x + y * y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public static void main(String[] args) {
Point[] points = new Point[10];
Random random = new Random();
for (int i = 0; i < points.length; i++) {
int x = random.nextInt(21) - 10; // 产生 -10 ~ 10 的随机整数
int y = random.nextInt(21) - 10; // 产生 -10 ~ 10 的随机整数
points[i] = new Point(x, y);
}
Arrays.sort(points, (p1, p2) -> Double.compare(p1.distanceToOrigin(), p2.distanceToOrigin()));
for (Point point : points) {
System.out.println(point + " " + point.distanceToOrigin());
}
}
}
```
输出结果:
```
(0, 0) 0.0
(1, 1) 1.4142135623730951
(-1, -1) 1.4142135623730951
(3, -3) 4.242640687119285
(4, -6) 7.211102550927978
(-6, 9) 10.816653826391969
(10, -8) 12.806248474865697
(-9, -9) 12.727922061357855
(-10, 10) 14.142135623730951
(10, 10) 14.142135623730951
```
阅读全文