01: import java.util.Random;
02: 
03: /**
04:    This class simulates a needle in the Buffon needle experiment.
05: */
06: public class Needle
07: {
08:    /**
09:       Constructs a needle.
10:    */
11:    public Needle()
12:    {
13:       hits = 0;
14:       tries = 0;
15:       generator = new Random();
16:    }
17: 
18:    /**
19:       Drops the needle on the grid of lines and 
20:       remembers whether the needle hit a line.
21:    */
22:    public void drop()
23:    {
24:       double ylow = 2 * generator.nextDouble();
25:       double angle = 180 * generator.nextDouble();
26:       
27:       // Computes high point of needle
28:       
29:       double yhigh = ylow + Math.sin(Math.toRadians(angle));
30:       if (yhigh >= 2) hits++;    
31:       tries++;
32:    }
33: 
34:    /**
35:       Gets the number of times the needle hit a line.
36:       @return the hit count
37:    */
38:    public int getHits()
39:    {
40:       return hits;
41:    }
42: 
43:    /**
44:       Gets the total number of times the needle was dropped.
45:       @return the try count
46:    */
47:    public int getTries()
48:    {
49:       return tries;
50:    }
51:         
52:    private Random generator;
53:    private int hits;
54:    private int tries;
55: }