Java 一个简单的距离工具类

1. 点类

package Fengzhang_Anli;

public class Point {
    // 成员变量
    private double x;
    private double y;
    
    // 构造方法
    Point(){
        
    }

    public Point(double x,double y) {
        this.x = x;
        this.y = y;
        
    }
    
    // 成员方法
    public double getX() {
        return x;
    }
    
    public double getY() {
        return y;
    }
    
    
    
}

 

2. 距离工具类

package Fengzhang_Anli;

public class Distance {

    // 求距离的工具类
    public static double distance(Point p1, Point p2) {
        double a = Math.pow((p1.getX()-p2.getX()),2);
        double b = Math.pow((p1.getY()-p2.getY()),2);
        return Math.sqrt(a+b);
    }
    
}

 

3. 测试类

package Fengzhang_Anli;

public class Distance_Test {

    public static void main(String[] args) {
        Point p1 = new Point(2,2);
        Point p2 = new Point(2,1);
        System.out.println("(2,2)与(2,1)的距离:" + Distance.distance(p1, p2));

    }

}

 

4. 运行结果

 

posted @ 2020-10-14 23:30  ZengZG  Views(195)  Comments(0Edit  收藏  举报