Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                    
                
        

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

我有两个类“ 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/

10-12 01:27