このプログラムは、乱数のスロー (x、y 座標) によって Pi を計算し、プロセス全体を何度も繰り返すために使用されます。
コード double average = average(pi) の最後の行でエラーが発生し、それを使用して average メソッドで宣言しても、シンボル変数 pi が見つからないというエラーが表示されます。
/*
@author
@version January 8th 2016
*/
import java.util.Scanner;
import java.util.Random;
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts2 {
public static int numThrows;
public static int numTrials;
public static int misses;
public static int hits;
public static void prompt() {
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
numTrials = in.nextInt();
}
public static double[] randomX( int numThrows){
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts < numThrows - 1) {
cordX[i] = Math.random();
i++;
darts++;
}
return cordX;
}
public static double[]randomY(int numThrows) {
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts < numThrows) {
cordY[i] = Math.random();
i++;
darts++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY) {
int ii = 0;
int i = 0;
hits = 0;
misses = 0;
for(i = 0; i < numThrows; i++) {
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1) {
hits++;
} else{
misses++;
}
ii++;
}
}
public static double calcPi(int misses, int hits) {
int total = hits + misses;
double pi = 4 * ((double)hits / total);
return pi;
}
public static void print(double pi, int numThrows) {
System.out.printf("\nThe pi estimate for this trial is: " + pi);
}
public double average(double[] pi) {
double sum = 0;
double average;
for(int i = 0; i < pi.length; i++) {
sum = sum + pi[i];
}
average = (double)sum/pi.length;
return average;
}
public static void main(String[] args)throws IOException {
prompt();
int x = 0;
for(x = 0; x < numTrials; x++) {
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
getHits(numThrows, cordX, cordY);
double pi = calcPi(misses, hits);
print(pi, numThrows);
}
double average = average(pi);
}
}