mardi 23 décembre 2014

ArrayIndexOutOfBoundsException error in darts file

The purpose of this program is to find an estimate of pi. At first it ran but the values were too large (20,30,,40,etc) and now it does not even compile. I get the ArrayIndexOutOfBoundsException error. How would you go on fixing the code? Thanks.



import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
import java.io.File;
import java.io.IOException;
public class Darts
{
public static double[] getPi(double[] pi, int trials, int times, int counter)
{
for (int loop = 0; loop < trials; loop++)
{
for (int r = 0; r < times; r++)
{
double x = Math.random();
double y = Math.random();


if (Math.pow(x,2) + Math.pow(y,2) <= 1)
{
counter++;
}


}
pi[trials] = 4 * (double) counter / times;

}
return pi;
}
public static void printResults(double[] pi, int trials, double average)
{
for (int x = 0; x < trials; x++)
{
System.out.println("Trial [ " + x + "]: pi = " + pi[x]);
}
System.out.println("Estimate of pi = " + average );
}

public static void main (String [ ] args) throws IOException
{
Scanner in = new Scanner(System.in);
int counter = 0;
double y = 0;
double x = 0;
double radius = 1.0;
Random randNumList = new Random();


System.out.println("How many times darts should be thrown in a trial?");
int times = in.nextInt();

System.out.print("How many trials will there be?");
int trials = in.nextInt();
System.out.println(" " + trials + " trials");

double pi[] = new double[trials];
pi = getPi(pi, times, trials, counter);

double sumPi = 0.0;
for (int l = 0; l < trials; l++)
{
sumPi += pi[l];
}
double average = sumPi/counter;
printResults(pi, trials, average);


}
}




Aucun commentaire:

Enregistrer un commentaire