Example 2: Design and Write a Method

The signature for our method is:

public static Rectangle calcBoundRect(int centerX, int y, int diameter)

Before we can write the body of the method, we need to design it by determining the algorithm it should use.

The algorithm for determining a bounding rectangle from the center and diameter of a circle is:

  1. Determine the radius of the circle (diameter / 2).

  2. Calculate the top left x coordinate of the rectangle, which is the x coordinate for the center of the circle minus the radius.

  3. Calculate the top left y coordinate of the rectangle, which is the y coordinate for the center of the circle minus the radius.

  4. The answer is a rectangle with the calculated x and y coordinates and a width and height that both match the diameter of the circle.

You may have noticed that this calculation requires a bit of math. Luckily we can figure it out once, hide the details in the method, and then just call the calcBoundRect() method to do the calculation for us.

Code for the calcBoundRect() Method


/**
 *  Returns the bounding rectangle of the specified circle.
 */

public Rectangle calcBoundRect(int centerX, int centerY, int diameter)
{
	Rectangle r;
	int topLeftX, topLeftY;

	// 1. Determine the radius of the circle (diameter / 2).

	int radius = diameter / 2;

	// 2. Calculate the top left x coordinate

	topLeftX = centerX - radius;

	// 3. Calculate the top left y coordinate.

	topLeftY = centerY - radius;

	// 4. The answer is a rectangle, which is returned.

	r = new Rectangle(topLeftX, topLeftY, diameter, diameter);

	return(r);
}