java 定义类Point描述笛卡尔坐标系上的点,并在该类中编写计算两点间距离的方法distance()。编写公有类TestPoint测试Point类的功能,创建若干点,并输出各点之间的距离。
时间: 2023-05-12 12:07:36 浏览: 134
好的,以下是Java代码:
```
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distance(Point other) {
double dx = this.x - other.x;
double dy = this.y - other.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
public class TestPoint {
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
Point p3 = new Point(-1, 2);
System.out.println("Distance between p1 and p2: " + p1.distance(p2));
System.out.println("Distance between p1 and p3: " + p1.distance(p3));
System.out.println("Distance between p2 and p3: " + p2.distance(p3));
}
}
```
输出结果为:
```
Distance between p1 and p2: 5.0
Distance between p1 and p3: 2.23606797749979
Distance between p2 and p3: 5.830951894845301
```
这是一个简单的Point类和TestPoint类,可以计算两点之间的距离并输出结果。
阅读全文