import javax.swing.*; import java.awt.event.*; import java.awt.*; class Six extends JFrame { Seven component; Six(String title, int width) { this.component = new Seven(); this.add( this.component ); this.setSize(width, width); this.setTitle(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { Six frame = new Six("Finding PI", 600); frame.component.calculate(); } } class Seven extends JComponent { int times, size, inside, total; Point center; public void paintComponent(Graphics g) { this.size = this.getHeight(); this.center = new Point(size/2, size/2); this.total = this.inside = 0; g.setColor(Color.BLUE); g.drawOval(0, 0, this.size, this.size); if (this.times > 0) { for (int i = 0; i < this.times; i = i + 1) { Point p = new Point(size); if (p.distanceTo(this.center) < size/2) { this.inside += 1; g.setColor(Color.RED); } else g.setColor(Color.BLUE); g.drawLine(p.x, p.y, p.x, p.y); this.total += 1; } System.out.println( "In " + this.times + " simulation steps PI is estimated to " + 4.0 * this.inside / this.total ); } } void calculate() { String input = JOptionPane.showInputDialog("How many times?"); if (input == null || input.equals("bye")) System.exit(0); else { try{ this.times = Integer.parseInt( input ); this.repaint(); } catch (Exception e) { System.out.println("Please enter a number or bye."); } finally { this.calculate(); } } } } class Point { int x, y; Point(int size) { this((int)(Math.random() * size), (int)(Math.random() * size)); } Point(int x, int y) { this.x = x; this.y = y; } double distanceTo(Point other) { return Math.sqrt( Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2) ); } }