In writing RectangleIntersection.java in lab today, I constructed a big 10x10 rectangle located at (5,5), which is shown here in blue. Then I constructed a small 8x4 rectangle at (0,0), which is shown here in red. Then I calculated the area of the intersection (marked in green).
However, the result we got in class for the area was -3. This was because the intersection rectangle was of size 3 x -1. (?!)
After lab, I realized my error. I was thinking of these Rectangles in terms of normal geometric rectangles. However, we're using java.awt.Rectangle
here. awt
is short for Abstract Windowing Toolkit, which is used to build graphical user interfaces and draw things on the screen. The convention when working on a screen is that the (0,0) is in the upper left corner of the screen. The x-axis increases to the right and the y-axis increases as you go down the screen! (The Rectangle class does not state this explicitly in the API, though.)
So what I'd actually constructed with my program was this:
As you can see, the two rectangles don't overlap. On the x-axis, they overlap by 3, but they are 1 unit away from each other on the y-axis--hence, the 3 x -1 result. As the API explains, it is possible to construct java.awt.Rectangles with negative dimensions (though this means the rectangle is nonexistent in space).
So I changed the size of the small rectangle from 8x4 to 8x9 so that they do overlap using the graphical coordinate scheme:
Now I get the area I expected: 12 units2.