-5

将以下方法添加到 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) ;
 }
 }
4

3 回答 3

2

other.getX()而不是other, 与 y 相同。Other 是 Point 类的一个实例。你想通过这个值的 getter 来访问 other 的 x 值,getX。读这个:

http://docs.oracle.com/javase/tutorial/java/concepts/index.html

于 2013-01-23T13:43:19.057 回答
1
return Math.abs(x - other)+ Math.abs(y - other);

上面的行应该是:

return Math.abs(x - other.getX())+ Math.abs(y - other.getY());

为什么?

因为目前您正试图直接从整数中获取点对象,这是没有意义的。即使在逻辑上,你也不能明智地从一个整数中减去二维空间中的一个点。您需要从整数中获取特定值(other对象中的 x 和 y,通过调用适当的方法获得。)

与问题无关,但您也可以正确格式化您的代码!

于 2013-01-23T13:45:26.513 回答
0

这一行是错误的: Math.abs(x - other)+ Math.abs(y - other)

另一个是 Point 对象。您必须获取该 Point 对象的 x 和 y,然后进行减法运算

而是试试这个: return Math.abs(x - other.getX())+ Math.abs(y - othe.getY()) ;

于 2013-01-23T13:44:28.520 回答