2013-04-18 52 views
-1

嗨im新的java我不確定如何在java中使用類功能。我的老師給了我們point2d類,並希望我們在那裏使用這個函數。有一個函數調用distanceTo如何在java中使用不同的類功能

// return Euclidean distance between this point and that point 
public double distanceTo(final Point2D that) { 
    final double dx = this.x - that.x; 
    final double dy = this.y - that.y; 
    return Math.sqrt(dx*dx + dy*dy); 
} 

我不知道我是如何實現這一點。這是我的代碼

public static int calc(int amount) 
{ 
     for (int t = 0; t < amount; t++) 
     { 
      double current = 0; 
      double x = StdRandom.random(); 
      double y = StdRandom.random(); 
      Point2D p = new Point2D(x, y); 
      if (current < distanceTo(Point2D p)) 
      { 
      } 

我試圖用distanceTo(p)distanceTo(Poin2D)並沒有什麼作品。

在此先感謝

回答

0

public static int calc(int amount)static,而distanceTo不是。

對於不是staticdistanceTo需要包含對象的實例,例如:new Point2D().distanceTo(...)

然後,您可以撥打distanceTo給你一些Point2D你已經有了,說p2

p2.distanceTo(p); 

或者你可以嘗試打開distanceTostatic方法,它可以獲取兩個點作爲參數:

public static double distanceTo(final Point2D one, final Point2D that) { 
    final double dx = one.x - that.x; 
    final double dy = one.y - that.y; 
    return Math.sqrt(dx*dx + dy*dy); 
} 

並且使用它:

distanceTo(p, p2); 

PS .:作爲替代,也許您的解決方案是將calc變爲非靜態。也許,你應該嘗試一下。

+0

如果該功能是由靜態的,它需要兩個參數。 – michaelb958 2013-04-18 04:54:38

1

因爲它是類函數,所以還需要對類的實例的引用。在這種情況下,類似於

Point2D b; 
p.distanceTo(b); // Invoke distanceTo on b from the point of view of p 

這是因爲您的方法需要2個要引用的對象。調用對象p和傳遞的對象b,在您的函數中分別被稱爲thisthat

0

要調用類的非靜態方法,請使用.運算符。

要調用distanceTo,使用語法如下:

p.distanceTo(p); 

,如果它是靜態的,使用的類名.操作

Point2D.distanceTo(p); 
相關問題