Point类的位置

时间:2014-10-20 20:08:03

标签: java

有人可以告诉我我做错了什么吗?我在代码下面列出了错误。我刚刚用Java弄湿了,所以请你好好回答。

//The Point class definition
public class Point 
    {
    private int x;
    private int y;

   // Constructors
    public Point() 
    {
      x = 0;
      y = 0;
   }

    public Point(int newX, int newY) 
    {
      x = newX;
      y = newY;
    }
  // Getters and Setters
    public int getX() 
    {
      return x;
    }

     public int getY() 
    {
      return y;
    }

    public void setX(int newX) 
    {
      x = newX;
    }

    public void setY(int newY) 
    {
      y = newY;
    }

   public double distance(Point another) //takes one parameter of Point type and returns a double
    {
      double xDiff = x - another.x;
      double yDiff = y - another.y;
      return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
    }

    public void translate(int dx, int dy)
//takes two int parameters for values used to translate,returns a new point with a new location (do not update current location) point. 
    {                     
        x = x + dx;
        y = y + dy;
    }  

    public void setXY(int newX, int newY) //updates the location of the point all at one time.
    {
      x = newX;
      y = newY;
    }

    public String toString() 
    {
      return "(" + x + "," + y + ")";
    }

}

运行驱动程序时出错:

 PointDriver.java:24: error: method distance in class Point cannot
 be applied to given types;
        pt3 = pt2.distance(3, -10);
                 ^    required: Point    found: int,int    reason: actual and formal argument lists differ in length 
 PointDriver.java:31: error: method distance in class Point cannot be
 applied to given types;
        pt1 = pt1.distance(4, -2);
                 ^    required: Point

4 个答案:

答案 0 :(得分:0)

看起来错误正在发生,因为您将两个整数传递给期望Point的方法。但是,如果没有看到错误中实际引用的代码,那么很难确定。

我想猜你的路线:

pt3 = pt2.distance(3, -10);

应该看起来像这样:

pt3 = pt2.distance(new Point(3, -10));

或者可能是这样的:

Point p4 = new Point(3,-10);
pt3 = pt2.distance(pt4);

或许您应该在Point中编写一个新方法:

public double distance(int x, int y) 
{
    Point p = new Point(x,y);
    return this.distance(p);
}

答案 1 :(得分:0)

距离nethod需要一个Point而不是一个分隔坐标。 使用:

pt3 = pt2.distance(new Point(3, -10));

答案 2 :(得分:0)

你应该传递距离一个Point对象而不是2个整数。尝试这样的事情:

pt2.distance(new Point(3, -10));

这就是你可能正在寻找的东西。

答案 3 :(得分:0)

问题是,你没有用Point调用方法距离。当你这样做时它会起作用:

 Point t = new Point(4, -2);
 pt1.distance(t);

另一个问题在于

pt1 = pt1.distance(4, -2),因为pt1是一个点,但返回的值是一个double。

你可以这样做:

double p1 = pt1.distance(4, -2)