Search code examples
javaobjectparametersdistancepoints

Method takes another object as a parameter


I am doing homework for java programming. I am asked to write a method that returns a distance between two points. I should use given formula that distance = square root((x2 - x1)*(x2 - x1) +(y2 - y1)*(y2 - y1)).

In the below codes, an object a will be contained current coordinate x1 and y1 and b will be coordinate x2 and y2, passed to move at some where.

How can I write the method in this class without having other classes and other elements such as x2, y2? In the objects there are two values but how can I assign each to x1 and x2, and y1 and y2? I found definition of vector for java but I am not sure it is applicable for this. Does anybody have an idea?

public class MyPoint{
    private int x;
    private int y;
}

public MyPoint(int x, int y){
        this.x = x;
        this.y = y;
} 

public int distanceTo(MyPoint a, MyPoint b){
    MyPoint.x1 = a;
    MyPoint.y1 = a;
    MyPoint.x2 = b;
    MyPoint.y2 = b;
    double distance = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    return distance;
}
}

Solution

  • The distanceTo method should only take one parameter, a MyPoint object, not two parameters:

    public double distanceTo(MyPoint other) {
      // ...
    }
    

    The first object of the comparison will be the current object, the one whose method is being called.

    Then in the method body you compare the current object's fields, the this.x and this.y with the x and y values of the object passed in to the method's parameter, other.x and other.y.

    Also, the method probably should return a double, not an int as you have it defined.

    Regarding,

    How can I write the method in this class without having other classes and other elements such as x2, y2?

    I'm not sure exactly what you mean by this.