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