用Java写类和对象之坐标系中两点距离计算
时间: 2024-05-01 13:17:34 浏览: 17
可以通过以下步骤来用Java写类和对象之坐标系中两点距离计算:
1. 创建一个Point类,用于表示一个二维平面上的点,该类应该具有两个属性x和y分别表示该点的横坐标和纵坐标,还应该有一个计算距离的方法。
```
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 p) {
double dx = this.x - p.x;
double dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
```
2. 创建一个Main类,用于测试Point类的功能。
```
public class Main {
public static void main(String[] args) {
Point p1 = new Point(1.0, 2.0);
Point p2 = new Point(4.0, 6.0);
double distance = p1.distance(p2);
System.out.println("The distance between p1 and p2 is: " + distance);
}
}
```
3. 运行Main类,输出结果为"The distance between p1 and p2 is: 5.0",表示p1和p2两个点的距离为5.0。
以上是用Java写类和对象之坐标系中两点距离计算的方法。