Add the following method to the Point class: public double distance(Point other)
ID: 3664200 • Letter: A
Question
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.
Explanation / Answer
public class Point { private int x; private int y; // constructs a new point at the origin, (0, 0) public Point() { this(0, 0); // calls Point(int, int) constructor } // constructs a new point with the given (x, y) location public Point(int x, int y) { setLocation(x, y); } // returns the distance between this Point and (0, 0) public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // returns the x-coordinate of this point public int getX() { return x; } // returns the y-coordinate of this point public int getY() { return y; } // sets this point's (x, y) location to the given values public void setLocation(int x, int y) { this.x = x; this.y = y; } // returns a String representation of this point public String toString() { return "(" + x + ", " + y + ")"; } // shifts this point's location by the given amount public void translate(int dx, int dy) { setLocation(x + dx, y + dy); } public double Distance(Point other){ /// int distance = Math.abs(x-other) + Math.abs(y-other); return Math.abs(x - other.getX())+ Math.abs(y - other.getY()); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.