2013-01-23 30 views
-4

添加以下方法给Point类:实例方法公众诠释manhattanDistance(点等)不会编译

public int manhattanDistance(Point other) 

返回当前点对象与给定其他点object.The之间的“曼哈顿距离”曼哈顿距离是指两个地点之间的距离,如果只能水平移动 或垂直移动,就好像在曼哈顿的街道上驾驶一样。在我们的例子中,曼哈顿距离是其坐标差值绝对值的总和 ;换句话说,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) ; 
} 
} 
+5

你读过你得到的编译错误吗?它应该指出你的错误,并且相当自我解释。 – assylias

+3

@assylias ...难以指出明显的......哦,不,其他人只是毁了它... – ppeterka

+1

[我看起来像古茹?](http://programmer.97things.oreilly。 com/wiki/index.php/The_Guru_Myth) –

回答

0

此行是错误的:Math.abs(X - 等)+ Math.abs(Y - 其他)

另一种是点object.You必须得到x和然后执行减号操作

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

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

上面一行应该是:

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

为什么?

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

与问题无关,但您也可以很好地格式化代码!

+0

格式化确实会有很大帮助^^ –