gpt4 book ai didi

java - darts 文件中的 ArrayIndexOutOfBoundsException 错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:19 26 4
gpt4 key购买 nike

该程序的目的是求出 pi 的估计值。起初它可以运行,但值太大(20,30,,40,etc),现在它甚至无法编译。我收到 ArrayIndexOutOfBoundsException 错误。 您将如何继续修复代码?谢谢。

    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);


}
}

最佳答案

您的线路:

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

应该是:

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

关于java - darts 文件中的 ArrayIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27629297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com