CS302 Exam 2 Spring 2013 Reference Solution Part I: Write a complete program import java.util.Scanner; public class EstimatePI { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); System.out.print("Enter the number of darts: "); if ( !scnr.hasNextInt() ) errorMsg(); int darts = scnr.nextInt(); // random throws per trial if ( darts < 1 ) errorMsg(); // The simulation int side = 2; // the length of the side of a rectangle int radius = side/2; // the radius of the circle int inCircle = 0; for ( int p=0; p < darts; p++ ) { double x = Math.random()*side; double y = Math.random()*side; double d = Math.sqrt(Math.pow(x-radius,2)+ Math.pow(y-radius,2)); if ( d <= radius ) inCircle++; } double pi_est = 4.0*(inCircle/(double)darts); System.out.print("Darts IN="+inCircle); System.out.println(" PI="+pi_est); } private static void errorMsg() { System.out.println("Must [be|enter] a positive integer!"); System.exit(-1); } }