计算2D和3D中2点之间的距离

时间:2014-05-29 16:09:20

标签: java math 3d

我只是想解决一个非常简单的问题,但我有一些小问题。希望你能快速帮助初学者;)

我有两个类'Point'和'Point3D'看起来像这样:

public class Point {
    protected double x;
    protected double y;

    Point(double xCoord, double yCoord){
        this.x = xCoord;
        this.y = yCoord;
    }

    public double getX(){
        return x;
    }

    public double getY(){
        return y;
    }

    public static double distance(Point a, Point b)
    {
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    public static void main(String[] args) {
        Point p1 = new Point(2,2);
        Point p2 = new Point(5,6);
        System.out.println("Distance between them is " + Point.distance(p1, p2));
    }
}

而且:

public class Point3D extends Point {
    protected double z;

    Point3D(double x, double y, double zCoord){
        super(x, y);
        this.z = zCoord;
    }

    public double getZ(){
        return z;
    }

    public static double distance(Point p1, Point p2){
        double dx = p1.x - p2.x;
        double dy = p1.y - p2.y;
        double dz = p1.z - p2.z;
        return Math.sqrt(dx * dx + dy * dy + dz *dz);
    }

    public static void main(String[] args) {
        Point3D p1 = new Point3D(-4,2,5);
        Point3D p2 = new Point3D(1,3,-2);
        System.out.println("Distance between them is " + Point3D.distance(p1, p2));
    }
} 

我现在的问题如下: 如果我保留这样的代码,我的Eclipse会说“z无法解析为字段”,作为一种可能的解决方案,我应该在我的类'Point'中创建它。 在这之后,类'Point3D'编译但不计算正确答案..

问候,

1 个答案:

答案 0 :(得分:3)

将Point3D距离方法的签名更改为:

public static double distance(Point3D p1, Point3D p2){

您的参数只有Point种类型,而且没有z