我目前正面临一个问题,无法找到方法。这是问题......
完成以下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);
我该如何解决?
答案 0 :(得分:0)
我认为您的作业要求您向Point
课程添加cloning method,如下所示:
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); }
}
答案 1 :(得分: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());
}
答案 2 :(得分: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;
}
}