2013-01-23 31 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

格式化確實會有很大幫助^^ –