首页 > 解决方案 > 使用构造函数计算两点之间的欧几里得距离

问题描述

我正在编写一个 Java 程序,该程序使用以下构造函数实现 Point 数据类型:

点(双 x,双 y,双 z)

以及以下 API:

java点2.1 3.0 3.5 4 5.2 3.5

第一点是(2.1,3.0,3.5)

第二点是(4.0,5.2,3.5)

他们的欧几里得距离是 2.90

该程序无法编译,但我不知道为什么。我是编程新手,所以我按照在线和 Codecademy 的一些步骤尝试访问构造函数中的对象,但我认为我做错了。任何建议将不胜感激。

public class Point {
    double x1;
    double y1;
    double z1;
    double x2;
    double y2;
    double z2;
    
    public Point(double x, double y, double z){

        x1 = x;
        y1 = y;
        z1 = z;
        x2 = x;
        y2 = y;
        z2 = z;
    }
    
    public double distanceTo(Point q){
    return Math.sqrt(Math.pow((x1-x2), 2.0) + Math.pow((y1-y2), 2.0) + Math.pow((z1-z2), 2.0));
    
    }
    double x3 = x1-x2;
    double y3 = y1-y2;
    double z3 = z1-z2;

    public String toString() {
        return "(" + x3 + ", " + y3 + ", " + z3 + ")";
    }
    
    public static void main (String[]args){
        
        Point pointOne = new Point(args[0]);
        Point pointTwo = new Point(args[1]);
        Point distance = new distanceTo();
        
        System.out.println("The first point is " + "(" + pointOne + ")");
        System.out.println("The second point is " + "(" + pointTwo + ")");
        System.out.println("Their Euclidean distance is " + distance);
    }
}

标签: javaclassconstructordoubleeuclidean-distance

解决方案


有几件事:

首先,您的 Point 类应该只需要一组变量。只需制作一组并构造两个点对象。

在 distanceTo() 方法中,通过执行 q.x1、q.y1 等来访问其他点的坐标。

在 main 方法中,距离应该是 pointOne 到 pointTwo 的距离的两倍。这是对我有用的代码

class Point {
    double x1;
    double y1;
    double z1;
    public Point(double x, double y, double z){
    //each point object only needs one x, y and z
        x1 = x;
        y1 = y;
        z1 = z;
    }

    public double distanceTo(Point pointTwo){
        return Math.sqrt(Math.pow(pointTwo.x1-x1, 2.0) + Math.pow(pointTwo.y1-y1, 2.0) + Math.pow(pointTwo.z1-z1, 2.0));
        //formula is sqrt((p2.x-p1)^2 + (p2.y-p1.y)^2 + (p2.z - p1.z)^2
    }


    public String toString() {
        return "(" + x1 + ", " + y1 + ", " + z1 + ")";
        //we don't need a diff set of variables here
    }

    public static void main (String[]args){
        //make two diff points with coords
        Point pointOne = new Point(2.1, 3.0, 3.5);
        Point pointTwo = new Point(4.0,5.2, 3.5);
        double distance = pointOne.distanceTo(pointTwo);
        //uses point two as the parameter (x2, y2, z2 in formula)
        System.out.println("The first point is " + "(" + pointOne + ")");
        System.out.println("The second point is " + "(" + pointTwo + ")");
        System.out.println("Their Euclidean distance is " + distance);
    }
}

推荐阅读