将以下方法添加到 Point 类:
public int manhattanDistance(Point other)
返回当前 Point 对象和给定的其他 Point 对象之间的“曼哈顿距离”。曼哈顿距离是指两个地方之间的距离,如果一个人只能通过水平或垂直移动在它们之间移动,就像在曼哈顿的街道上行驶一样。在我们的例子中,曼哈顿距离是它们坐标差的绝对值之和;换句话说,点之间的差异x
加上
y
点之间的差异。
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 int manhattanDistance(Point other){
/// int distance = Math.abs(x-other) + Math.abs(y-other);
return Math.abs(x - other)+ Math.abs(y - other) ;
}
}