Search code examples
javapoint

How to compute distance between my original and supplied point in Java


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); 
}

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

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

Would this be fine?


Solution

  • You didn't use in the parameter.

    public double distance(Point other) {
    
            double d = Math.pow(other.getX()- getX(), 2) + Math.pow(other.getY() - getY(), 2);
    
            return Math.sqrt(d); 
    }