如何用Java计算原始点和提供点之间的距离

如何用Java计算原始点和提供点之间的距离,java,point,Java,Point,我试图计算我的“原始点”和我提供的点x的距离。我不确定我是否做对了。我主要关注的是: 如何参考原始点和提供点的坐标?这里的数学是基础的,所以我对此很有信心 感谢您的帮助。PS我对Java是新手 因此,我也在考虑在函数中为我的点赋值: 公共双倍距离(x点){ 点x=新点(x,Y); double d=Math.pow(this.X-X.X,2)+Math.pow(this.Y-X.Y,2); 返回数学sqrt(d); } 这可以吗?您没有在参数中使用 public class Point {

我试图计算我的“原始点”和我提供的点x的距离。我不确定我是否做对了。我主要关注的是:

如何参考原始点和提供点的坐标?这里的数学是基础的,所以我对此很有信心

感谢您的帮助。PS我对Java是新手

因此,我也在考虑在函数中为我的点赋值:

公共双倍距离(x点){
点x=新点(x,Y);
double d=Math.pow(this.X-X.X,2)+Math.pow(this.Y-X.Y,2);
返回数学sqrt(d);
}

这可以吗?

您没有在参数中使用

public class Point {

private double X, Y;


  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {


    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d); 
}

在方法距离中,您将另一个点作为名为
x
(不是很好的名称)的变量传递,并且可以使用该变量访问其字段和方法:

public double distance(Point other) {

        double d = Math.pow(other.getX()- getX(), 2) + Math.pow(other.getY() - getY(), 2);

        return Math.sqrt(d); 
}

Y值也一样,然后你可以用这些值进行计算。

数学.sqrt((x1-x2)(x1-x2)+(y1-y2)(y1-y2))如果你有如下的类:

public double distance(Point x) {
     double currentPointX = this.getX();
     double otherPointX = x.getX();
}
public class Point {
    private double x;
    private double y;

    ...constructors and methods omitted
}
要计算点与另一点之间的距离,可以使用java标准方法,如下所示:

public double distance(Point x) {
     double currentPointX = this.getX();
     double otherPointX = x.getX();
}
public class Point {
    private double x;
    private double y;

    ...constructors and methods omitted
}

这不是这里的问题。从未说过这不是一个有效的答案;-)。我的评论只是想说,
Math.power
比简单的产品更贵。对于整数类型,应考虑精度,但对于浮点类型,则不应考虑精度。谢谢您的回答。但是为什么我们必须使用getX()方法呢?@user6969因为get访问器可能有一个逻辑。谢谢你的回答。你能检查一下我在编辑的答案中的方法是否也有效吗?另外,你真的必须使用getX()方法吗?@user6969你不必使用方法
getX()
,因为你在同一个类中,你也可以直接访问字段,尽管它们像你在问题中那样是私有的。在这种情况下,这没有什么区别。为什么
点x=新点(x,Y)是吗?您将丢失作为参数获得的数据,然后将一个点与自身进行比较。只要去掉那一行,代码就行了吗?@MarkusKauppinen好的,这很有道理。谢谢:)@SergeBallesta好的,但我为什么要在这里重写这一点呢?我不是在给点
x
赋值吗?