// Pi.java : calculate the value of PI import java.util.Random; class Pi { final static int nDefMax = 500; final static int nDefInterval = 50; // main public static void main(String args[]) { int nMax; int nInterval; // set the number of point if (args.length >= 1) nMax = SetLimit(args[0]); else nMax = nDefMax; // set the number of interval if (args.length >= 2) nInterval = SetInterval(args[1]); else nInterval = nDefInterval; // Calculate PI CalcPI(nMax, nInterval); } // SetLimit : Set the number of point static int SetLimit(String str) { int n; n = Integer.valueOf(str).intValue(); if (n <= 0) return nDefMax; else return n; } // SetInterval : Set the number of interval static int SetInterval(String str) { int n; n = Integer.valueOf(str).intValue(); if (n <= 0) return nDefInterval; else return n; } // CalcPI : Calculate PI static void CalcPI(int nMax, int nInterval) { int nCount; float x; float y; int nInside; Random rand; nInside = 0; rand = new Random(); for (nCount = 1; nCount <= nMax; nCount++) { x = rand.nextFloat(); y = rand.nextFloat(); // Is the point in the circle ? if (IsInside(x, y) == Boolean.TRUE) nInside++; if ((nCount % nInterval == 0) || (nCount >= nMax)) PrintPI(nCount, nInside); } } // IsInside : Check the point is in the circle static Boolean IsInside(float x, float y) { if ( ((x * x) + (y * y)) <= 1 ) return Boolean.TRUE; else return Boolean.FALSE; } // PrintPI : Print the value of PI static void PrintPI(int nTotal, int nInside) { float fPi; fPi = (float) nInside / nTotal * 4; System.out.println(nTotal + " Points : PI = " + fPi); } }