-1
建模密切的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 intersect otherRectangle.
public boolean intersects(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(isEmpty() || w.doubleValue() <= 0.0 || h.doubleValue() <= 0.0)
return false;
return (
x.doubleValue() + w.doubleValue() > x0.doubleValue() &&
y.doubleValue() + h.doubleValue() > y0.doubleValue() &&
x.doubleValue() < x0.doubleValue() + getWidth().doubleValue() &&
y.doubleValue() < y0.doubleValue() + getHeight().doubleValue()
);
}
}
當我執行下面的代碼:
// r1 has upperLeft corner at (0,4), width = 6, height = 4
// r2 has upperLeft corner at (5,1), width = 2, height = 1
Rectangle r1 = new Rectangle(new Coordinate(0,4), 6, 4);
Rectangle r2 = new Rectangle(new Coordinate(5,1), 2, 1);
boolean result = r1.intersects(r2);
答案是假的!通過在調試器中單步調試代碼,我看到的原因是因爲在返回值的第二個AND
條款:
return (
x.doubleValue() + w.doubleValue() > x0.doubleValue() &&
y.doubleValue() + h.doubleValue() > y0.doubleValue() && <=== problem is here
x.doubleValue() < x0.doubleValue() + getWidth().doubleValue() &&
y.doubleValue() < y0.doubleValue() + getHeight().doubleValue()
);
當上述代碼運行時,y=1
,h=1
和y0=4
。顯然,1+1 > 4
是虛假。所以這絕對是我的算法中的一個錯誤,但我直接從Rectangle2D#intersect
複製它,並沒有看到我出錯的地方。任何人有任何想法?提前致謝!
但您的兩個示例矩形不相交。 – Blub
但你的長方形**不**相交... –
謝謝@Edgar Boda(+1) - 但是怎麼樣? r1的左上角是(0,4),所以它的所有座標都是(0,0),(0,4),(6,4)和(6,0)。 r2s座標是(5,0),(5,1),(7,1)和(7,0)。 r2是在r1的右側「切成兩半」 – IAmYourFaja