定义一个描述二维点的类(如Point2D),提供不带参数和带参数的构造方法;
提供distance(int x, int y)和distance(Point2D p)方法用于计算两点之间的距离。
使用该类描述任意多边形,使用类的distantce方法计算此多边形的周长
private int x;// x坐标
private int y;// y坐标
// 不带参数的构造方法
public Point() {
}
// 带两个参数的构造方法
public Point(int x, int y) {
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;
}
// 求两点的距离
public int distance(Point b) {
return (int) Math.sqrt((this.x - b.getX()) * (this.x - b.getX()) + (this.y - b.getY()) * (this.y - b.getY()));
}
public static void test() {
Point A = new Point();
Point B = new Point(50, 60);
A.setX(80);
A.setY(100);
System.out.println("A: (" + A.getX() + "," + A.getY() + ") ");
System.out.println("B: (" + B.getX() + "," + B.getY() + ") ");
System.out.println("A->B 的距离为:" + A.distance(B));
}
public static void test2() {
System.out.println("------------------------------------------");
Point a = new Point(-10, 10);
Point b = new Point(10, 10);
Point c = new Point(10, -10);
Point d = new Point(-10, -10);
System.out.println("a: (" + a.getX() + "," + a.getY() + ") ");
System.out.println("b: (" + b.getX() + "," + b.getY() + ") ");
System.out.println("c: (" + c.getX() + "," + c.getY() + ") ");
System.out.println("d: (" + d.getX() + "," + d.getY() + ") ");
System.out.println("C为:" + (a.distance(b)+b.distance(c)+c.distance(d)+d.distance(a)));
}
public static void main(String[] args) {// 测试的main方法
test();
test2();
}