reset password
Author Message
rabbott
Posts: 1649
Posted 12:12 Jan 13, 2014 |

In the Rectangle class:

public Rectangle union(Rectangle that) {
        int newX = Math.min(this.getX(), that.getX());        
        int newY = Math.min(this.getY(), that.getY());
        int thisRightX = this.getX() + this.getWidth();       
        int thatRightX = that.getX() + that.getWidth();
        int thisRightY = this.getY() + this.getHeight();       
        int thatRightY = that.getY() + that.
getHeight();
        int newRightX = Math.max(thisRightX, thatRightX);
        int newRightY = Math.max(thisRightY, thatRightY);
        Rectangle r3 = new Rectangle(newX, newY, newRightX - newX, newRightY - newY);
        return
r3;
}

   

In the RectangleTest class:

@Test
public void testUnion() {
        Rectangle r1 = new Rectangle(0, 0, 100, 100);
        Rectangle r2 = new Rectangle(50, 50, 100, 100);
        Rectangle union = r1.union(r2);
        assertEquals(0, union.getX());      
        assertEquals(0, union.getY());
        assertEquals(150, union.getWidth());     
        assertEquals(150, union.getHeight());
        r3.setColor(Color.YELLOW);  // Other colors are in the Color class.
        r3.fill();
        r1.draw();       
        r2.draw();
}

 

 

Last edited by rabbott at 12:27 Jan 15, 2014.