用java编写平面坐标类Point并测试

编写平面坐标类Point并测试
定义一个平面坐标类Point,包含横坐标、纵坐标私有属性x和y,设置成员方法getX()、getY()、setX()、setY()和构造方法;设置equals方法可判断两坐标点是否相同,设置坐标的格式化输出方法toString();再设置一个静态方法distance计算两点间的距离。
再测试Point类:生成两个Point对象,判断是否相同,并计算两点之间的距离。

运行结果:



public class Pointtest {

public static void main(String[] args) {
Point point1 = new Point(0,0);
Point point2 = new Point(5,5);
Point point3 = new Point(5,5);
System.out.println(point1.equals(point2));
System.out.println(point2.equals(point3));
System.out.println(Point.distance(point1,point2));
System.out.println(Point.distance(point1,5,5));
System.out.println(Point.distance(0,0,5,5));
}

}
class Point{
private  int x;
private  int y;
public Point() {
super();
// TODO Auto-generated constructor stub
}
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public static double distance(int x, int y,int a,int b) {
return Math.sqrt((Math.pow((x-a), 2)+Math.pow((y-b), 2)));
}
public static double distance(Point p,int a,int b) {
return Math.sqrt((Math.pow((p.getX()-a), 2)+Math.pow((p.getY()-b), 2)));
}
public static double distance(Point a,Point b) {
return Math.sqrt((Math.pow((a.getX()-b.getX()), 2)+Math.pow((a.getY()-b.getY()), 2)));
}
}

温馨提示:答案为网友推荐,仅供参考
相似回答