如何在java中使用不同的类函数

时间:2013-04-18 04:50:34

标签: java class

你好我刚接触java我不确定如何在java中使用类函数。我的老师给了我们point2d课程,并希望我们在那里使用该功能。有一个函数调用distanceTo

// 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)但没有任何效果。

提前致谢

3 个答案:

答案 0 :(得分:1)

由于它是一个类函数,因此您还需要引用该类的实例。在这种情况下,像

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

这是因为您的方法需要引用2个对象。调用对象p和传递的对象b,在您的函数中分别称为thisthat

答案 1 :(得分:0)

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

如果不是staticdistanceTo需要一个对象的封闭实例,例如:new Point2D().distanceTo(...)

然后,您可以distanceTo向您发送Point2D已经拥有的p2p2.distanceTo(p);

distanceTo

或者您可以尝试将static转换为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);

并使用以下方式调用它:

calc

PS:作为替代方案,也许您的解决方案是将{{1}}变为非静态。你可以尝试一下。

答案 2 :(得分:0)

要调用类的非静态方法,请使用.运算符。

要致电distanceTo,请使用以下语法:

p.distanceTo(p);

如果是静态的,请使用带有.运算符的类名

Point2D.distanceTo(p);