Home » Java » How to compute distance between my original and supplied point in Java-Exceptionshub

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

Posted by: admin February 25, 2020 Leave a comment

Questions:
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?

How to&Answers:

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

Answer:

If you have a class like below:

public class Point {
    private double x;
    private double y;

    ...constructors and methods omitted
}

To calculate distance between your point and another one you can use the java standard method Math.hypot like below:

public double distance(Point other) {
   return Math.hypot(this.x - other.x, this.y - other.y);
}

Answer:

In the method distance you are passing the other point as variable with the name x (Not a very good name) and can access its fields and methods with that variable:

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

The same for the Y-value and you can then do your math with those values.

Answer:

Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2))