【发布时间】:2013-12-25 20:24:29
【问题描述】:
与 Java AWT 的 Rectangle2D 类密切建模,我有我的 Rectangle POJO:
public class Rectangle {
// The Coordinate of the upper-left corner of the Rectangle.
private Coordinate upperLeft; // upperLeft.getXVal() and upperLeft.getYVal()
// The width of the Rectangle.
private BigDecimal width;
// The height of the Rectangle.
private BigDecimal height;
// Determine if we wholly contains otherRectangle. (no touching sides).
@Override
public boolean contains(Rectangle otherRectangle) {
BigDecimal x = otherRectangle.getUpperLeft().getXVal();
BigDecimal y = otherRectangle.getUpperLeft().getYVal();
BigDecimal w = otherRectangle.getWidth();
BigDecimal h = otherRectangle.getHeight();
BigDecimal x0 = getUpperLeft().getXVal();
BigDecimal y0 = getUpperLeft().getYVal();
if(isSingularity() || w.doubleValue() <= 0.0 || h.doubleValue() <= 0.0)
return false;
return (
x.doubleValue() >= x0.doubleValue() &&
y.doubleValue() >= y0.doubleValue() &&
(x.doubleValue() + w.doubleValue()) <= (x0.doubleValue() + getWidth().doubleValue()) &&
(y.doubleValue() + h.doubleValue()) <= (y0.doubleValue() + getHeight().doubleValue())
);
}
}
当我执行以下代码时:
// r1 has upperLeft corner at (0,4), width = 6, height = 4
// r2 has upperLeft corner at (1,2), width = 1, height = 1
Rectangle r1 = new Rectangle(new Coordinate(0,4), 6, 4);
Rectangle r2 = new Rectangle(new Coordinate(1,2), 1, 1);
boolean result = r1.contains(r2);
答案是错误的!
注意,我写这篇文章是基于以下假设:
-
upperLeft坐标字段就是——矩形的左上角;这意味着: - 获取右上角坐标的伪代码为
(upperLeft.x + width, upperLeft.y) - 获取左下角坐标的伪代码为
(upperLeft.x, upperLeft.y - height) - 获取右下角坐标的伪代码为
(upperLeft.x + width, upperLeft.y - height)
那么,我认为我的返回值有些问题:
return (
x.doubleValue() >= x0.doubleValue() &&
y.doubleValue() >= y0.doubleValue() &&
(x.doubleValue() + w.doubleValue()) <= (x0.doubleValue() + getWidth().doubleValue()) &&
(y.doubleValue() + h.doubleValue()) <= (y0.doubleValue() + getHeight().doubleValue())
);
但我不知道我哪里出错了。有任何想法吗?
【问题讨论】:
-
尝试将返回语句拆分为多个值,看看哪个是错误的。
-
为什么这被否决了?它显示了一个SSCCE,是原创的、易于处理的并且显然是一个编程问题。
-
@TicketMonster 我添加了一个图表来帮助理解,请检查是否有帮助。