import java.awt.*; import java.applet.*; import java.util.Random; /** * This class draws random points in and around a circle. */ public class Monte7 extends Applet { private static Random randy; private int SIZE; private Image offScreenImage; private Graphics offScreenGraphics; public int numInside, numOutside; private int randomInRange(int low, int high) { return (Math.abs(randy.nextInt()) % (high-low+1)) + low; } private double distance(int x1, int y1, int x2, int y2) { return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)); } public void init() { randy = new Random(); Dimension dim = getSize(); SIZE = Math.min(dim.width, dim.height); drawCircle(); } public void drawCircle() { numInside = 0; numOutside = 0; offScreenImage = createImage(SIZE, SIZE); offScreenGraphics = offScreenImage.getGraphics(); Graphics g = getGraphics(); offScreenGraphics.clearRect(0,0,SIZE,SIZE); g.clearRect(0,0,SIZE,SIZE); offScreenGraphics.setColor(Color.red); g.setColor(Color.red); offScreenGraphics.fillOval(0, 0, SIZE, SIZE); g.fillOval(0, 0, SIZE, SIZE); } public void drawDots(int numPoints) { Graphics g = getGraphics(); for (int i = 0; i < numPoints; i++) { int x = randomInRange(0, SIZE); int y = randomInRange(0, SIZE); if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) { offScreenGraphics.setColor(Color.white); g.setColor(Color.white); numInside++; } else { offScreenGraphics.setColor(Color.black); g.setColor(Color.black); numOutside++; } offScreenGraphics.drawLine(x, y, x, y); g.drawLine(x, y, x, y); } } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } }