CS 101 (Spring 2000)
Lab 5: Slices of PI (Design Solution)

Lab Assigned
Design Due
(In class)

10 AM
(In Lab)
(In Lab)
Lab Due
(In class)
10 AM
15 Feb 18 Feb 22-33 Feb 29-30 Feb 03 Mar

Solution APIs for this lab

This class allows one to draw a circle and throw darts at it.

Coordinates within this class are with respect to the origin of the circle, at (0,0). Thus, the square goes from (-S/2, -S/2) to (S/2, S/2). Translation from my coordinates to Java's is handled by the private method drawLine, as explained below.

PI(int S, int n)
Draws an approximation of a circle. You must use recursion, but you cannot call the constructor recursively -- use a helper method. The diameter of the circle is S. The approximation uses (approximately) n line segments. No canvas is provided as a parameter so this class has to make its own. After the circle is drawn, a square of size SxS is drawn, so that the circle sits just inside the square.
int numThrown()
returns the number of darts thrown at the circle.
int numLandedIn()
returns the number of darts thrown at the circle that actually landed inside.
int numLandedOut()
returns the number of darts thrown at the circle that landed outiside the circle (but of course inside the containing SxS square.

Representation invariant:
numThrown() = numLandedIn() + numLandedOut()

From outside this class, we can compute an approximate to PI by

PI pi = new PI(100, 5);
double approx = 4.0 * pi.numLandedIn() / pi.numThrown();
void hurlDarts(int m)
throws m (additional) darts at the circle. You must do this part iteratively. Each dart is shown with a dot on the screen.
Other (You needn't have turned these in; I provide these to help you.)
private void cirrecur(int oldX, int inc)
the recursive circle-drawer, as explained in class
private int cirfunc(int x)
returns the circle's positive Y coordinate for the supplied value of x.
private boolean insideCircle(int x, int y)
returns true if the coordinates supplied are inside the circle; otherwise, false is returned.
private hurlDart()
throws as single dart at the circle,
  • If the dart lands inside the circle, the dot is shown in red
  • otherwise, the dot is shown in black
The instance variables are updated to reflect the count of those darts landing in and the total number thrown.
private void drawLine(myX1, myY1, myX2, myY2) (parameters are all int).
I think of the center of the circle as (0,0). This method draws a line using my coordinate system, so it has to translate to Java's coordinate system where the upper, left-hand corner is (0,0).

Suggested plan for implementation:

  1. Type in your constructor for PI.
  2. Type in some testing code in Startup to invoke your PI constructor.
  3. Work on the throwing-darts part first, not the circle-drawing part
  4. Get your accessors to work
  5. Now get your recursive circle-drawer to work.

Last modified 11:53:31 CST 01 March 2000 by Ron K. Cytron