Dartboard.java


Below is the syntax highlighted version of Dartboard.java from §9.3 Symbolic Methods.


/******************************************************************************
 *  Compilation:  javac Dartboard.java
 *  Execution:    java Dartboard N
 *  Dependencies: StdDraw.java
 *
 *
 ******************************************************************************/

public class Dartboard {

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);         // N-by-N lattice

        // dartboard background
        StdDraw.clear(StdDraw.LIGHT_GRAY);

        // large bullseye
        StdDraw.setPenColor(StdDraw.GRAY);
        StdDraw.filledCircle(.5, .5, .5);

        StdDraw.show();

        // throw random points at the dartboard
        StdDraw.setPenColor(StdDraw.BLACK);
        int yes = 0;
        for (int i = 0; i < N; i++) {
            double x = Math.random();
            double y = Math.random();
            if (x*x + y*y <= 1.0) yes++;
            StdDraw.point(x, y);
        }

        // results
        double fraction = 1.0 * yes / N;
        StdOut.println("Fraction that hit dartboard = " + fraction);
    }
}



Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.