我已经完成了程序的其余部分,而我只是对这些方法感到困惑。我们没有在课堂上讲这个,也没有在任何笔记上讲。我本身不想要答案,我只需要一双新鲜的眼睛。
编辑:忘记添加方法说明 一个方法contains(double x,double y),如果指定点(x,y)在此矩形内,则返回true。参见下图。 。一个方法contains(Rectangle 2Dangle)如果指定的矩形在此矩形内,则返回true。参见图。 .a方法重叠(矩形2D矩形),如果指定的矩形与此矩形重叠,则返回true。见图。
class Rectangle2D {
double x;
double y;
double width;
double height;
public Boolean Contains(double x, double y) {
return false;
}
public Boolean Contains(Rectangle2D R1) {
return false;
}
public Boolean Overlap(Rectangle2D R1) {
return false;
}
}
答案 0 :(得分:1)
一点点数学,实际上很简单。
class Rectangle2D {
double x;
double y;
double width;
double height;
/**
* This rectangle contains the specified point if
*
* The x coordinate of the point lies between x and x + width
*
* and
*
* The y coordinate of the point lies between y and y + height
*
* @param x - The x position of the coordinate to check
* @param y - The y position of the coordinate to check
* @return true if the specified coordinate lies within the rectangle.
*/
public boolean contains(double x, double y) {
return x >= this.x
&& y >= this.y
&& x <= this.x + this.width
&& y <= this.y + this.height;
}
/**
* The rectangle contains the specified rectangle if the rectangle contains both diagonally opposite corners.
*
* @param r - The rectangle to check.
* @return - true if the specified rectangle is entirely contained.
*/
public boolean contains(Rectangle2D r) {
return contains(r.x, r.y)
&& contains(r.x + r.width, r.y + r.height);
}
/**
* The rectangle overlaps the specified rectangle if the rectangle contains any of the corners.
*
* @param r - The rectangle to check
* @return - true if any corner of the rectangle is contained.
*/
public boolean overlaps(Rectangle2D r) {
return contains(r.x, r.y)
|| contains(r.x + r.width, r.y + r.height)
|| contains(r.x, r.y + r.height)
|| contains(r.x + r.width, r.y);
}
}