Reputation: 3
I am trying to understand why I am having a difficult time calling two different points into a method in order to determine the distance between the two points.
This is the text provided on the website "Practice-It", where I am currently working through problems:
Add the following method to the Point class:
public double distance(Point other)
Returns the distance between the current Point object and the given other Point object. The distance between two points is equal to the square root of the sum of the squares of the differences of their x- and y-coordinates. In other words, the distance between two points (x1, y1) and (x2, y2) can be expressed as the square root of (x2 - x1)2 + (y2 - y1)2. Two points with the same (x, y) coordinates should return a distance of 0.0."
I have tried multiple ways to get the points into the method without naming individual coordinates. I believe that I am only getting the coordinates of the first point and am trying to understand where I am going wrong as I've had this problem before. I realize that the "int x1 = p1.x", etc. is redundant and I could just type "p1.x" in the return, but I am wanting to see all of the moving parts individually. Thanks for your consideration and help.
public double distance(Point other){
Point p1 = new Point();
int x1 = p1.x;
int y1 = p1.y;
Point p2 = new Point();
int x2 = p2.x;
int y2 = p2.y;
return Math.sqrt(Math.pow(x * x2, 2) + Math.pow(y * y2, 2));
}
This is my result from one of the situations tested:
test #1:(5, 2) to (8, 6)
expected output:
5.0
5.0
your output:
0.0
0.0
differences:
1,2c1,2
< 5.0
< 5.0
> 0.0
> 0.0
result: fail
Upvotes: 0
Views: 1743
Reputation: 521083
Your comparison logic is off. Assuming that distance()
is a method inside the Point
class, then you should be comparing the x,y values of the incoming other
point against the x,y value in the class:
public double distance(Point other) {
int x1 = other.x;
int y1 = other.y;
return Math.sqrt(Math.pow(this.x * x1, 2) + Math.pow(this.y * y1, 2));
}
Note that is would be more ideal to provide getters for the x
and y
fields in Point
. Here is a more complete suggested refactor:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public double distance(Point other) {
int x1 = other.getX();
int y1 = other.getY();
return Math.sqrt(Math.pow(this.x * x1, 2) + Math.pow(this.y * y1, 2));
}
}
Upvotes: 1