-5

我目前面临一个问题,找不到方法。这是问题...

完成下面的 Point 类:

public class Point{
  private int x;
  private int y;
  public Point(int x, int y){
    this.x = x;
    this.y = y;
  }
}

因此,以下代码会产生以下输出:

public class TestClass{
  public static void testEqual(Point p1, Point p2){
    if (p1.equals(p2)){
      System.out.println("The two points are equal\n"+p1);
    }else{
      System.out.println("The two points are not equal");
      System.out.println("First Point: "+ p1);
      System.out.println("Second Point: " + p2);
    }
  }
  public static void main(String [] args){
    Point p1 = new Point(2,3);
    Point p2 = Point.clonePoint(p1);
    Point p3 = new Point(1,1);
    Point p4 = new Point(2,3);
    testEqual(p1,p2);
    testEqual(p1,p3);
    testEqual(p1,p4);
    testEqual(p2,p4);
  }
}

输出

The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are not equal
First Point: The X Coordinate is 2 and the Y Coordinate is 3
Second Point: The X Coordinate is 1 and the Y Coordinate is 1
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3

我可以理解所有事情,但除了这条线我该Point p2 = Point.clonePoint(p1); 如何解决?

4

3 回答 3

0

这就是你所需要的:

[注意最后一个方法'clone'是一个静态(类)方法,您可以通过在类名'Point'后面加上'.'作为前缀来访问它]。

public class Point {

    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "The X Coordinate is " + x + " and the Y Coordinate is " + y;
    }

    @Override
    public boolean equals(Object otherPoint) {
        if (this == otherPoint) return true;
        if (otherPoint == null || getClass() != otherPoint.getClass()) return false;

        Point point = (Point) otherPoint;

        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

    public static Point clonePoint(Point p) {
        return p != null ? new Point(p.x, p.y) : null;
    }
}
于 2013-06-06T20:17:31.887 回答
0

我认为您的作业希望您像这样向类添加克隆方法Point

public class Point{
  private int x;
  private int y;
  public Point(int x, int y){
    this.x = x;
    this.y = y;
  }
  public static Point clonePoint(Point p){ return new Point(p.x,p.y); }
}
于 2013-06-06T19:59:06.423 回答
0

添加get用于将点坐标返回到您的Point类的方法:

public int getX()
{
   return x;
}

public int getY()
{
   return y;
}

然后将以下clonePoint()静态方法添加到您的Point类中:

public static Point clonePoint(Point p)
{
   return new Point(p.getX(), p.getY());
}

然后将以下equals()方法添加到您的Point类中:

public boolean equals(Point p)
{
   return (p.getX() == getX()) && (p.getY() == getY());
}
于 2013-06-06T20:04:02.600 回答