展开全部
这个要求中 distance 返回应该是double类型,而不是int类型, 因为 两点之间的距离不636f70793231313335323631343130323136353331333363393034可能是整数,double强制转换为int可能会超过Integer的最大值,代码如下:public class Point {
private Integer x;
private Integer y;
/**
* @param x
* @param y
*/
public Point(Integer x, Integer y) {
super();
this.x = x;
this.y = y;
}
/**
* @return the x
*/
public Integer getX() {
return x;
}
/**
* @param x the x to set
*/
public void setX(Integer x) {
this.x = x;
}
/**
* @return the y
*/
public Integer getY() {
return y;
}
/**
* @param y the y to set
*/
public void setY(Integer y) {
this.y = y;
}
public double distance(Point p) {
if(null == p) {
p = new Point(0,0);//if p is null, default point x=0 and y=0
}
double result = 0;
result = Math.abs(Math.sqrt(Math.pow(this.getX().intValue() -p.getX().intValue(),2)+Math.pow(this.getY().intValue() -p.getY().intValue(),2)));
return result;
}
public static void main(String[] args) {
Point point1 = new Point(1,1);
Point point2 = new Point(0,-1);
double distance = point1.distance(point2);
System.out.println(distance);
}
}
打印结果:
2.23606797749979