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

标签 java math 3d

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

我有 2 个类“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”类会编译,但不会计算出正确的答案..

问候,

最佳答案

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

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

参数只有 Point 类型,没有 z

关于java - 计算 2D 和 3D 中 2 点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937825/

相关文章:

flash - 雪球中随机雪的数学方程

c++ - Raku 中 C++ 和 NativeCall 之间的输出不同

java - 重新实例化 jpanels

java - 确定等距游戏和不规则形状的绘制顺序 (Java)

javascript - 美元金额的上限

ios - SceneKit 对象在它们的边界框而不是沿着网格发生碰撞

python - openGL(pyglet) 3d 场景无法在 AMD 显卡上正确渲染

java - 如何通过.apk传递dalvik命令行参数?

java - java中的集合map和HashMap

c++ - 没有着色器的 OpenGL 实例化渲染