基本上,我必须进行 1000 次试验。每次试用都是我成功挑选“带奖瓶盖”的时候。因此,每次我获得该奖品时,我还必须查看我在获得该奖品之前经历了多少瓶盖。我最终应该输出的是平均需要经过多少瓶盖才能找到奖盖。
我无法在我的程序中获得平均数量的瓶子,这就是我需要帮助的地方。我的平均结果最终并不正确。至于文件的输入和输出,这是任务的一部分,我已经想通了,所以我不需要帮助。还有一件事,前两行 outputFile.println 代码只是为了测试程序是否正常工作。
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
import java.util.Random;
public class BottleCapPrize
{
public static void main(String [] args) throws IOException
{
PrintWriter outputFile = new PrintWriter(new File("MonteCarlo.txt"));
Random randNum = new Random();
int bottleCapNumber = 0;
int wins = 0;
int capsOpened = 0;
for(int i = 1; i <= 1000; i++)
{
bottleCapNumber = randNum.nextInt(5);
while(bottleCapNumber != 0)
{
bottleCapNumber = randNum.nextInt(5);
capsOpened++;
}
if(bottleCapNumber == 0)
{
capsOpened++;
wins++;
}
}
outputFile.println(capsOpened);
outputFile.println(wins);
int averageNumberOfBottles = (int)(((double)wins / (double)capsOpened) * 10);
outputFile.println("The average amount of bottles that need to be opened are: " + averageNumberOfBottles);
outputFile.close();
Scanner inputFile = new Scanner(new File("MonteCarlo.txt"));
while(inputFile.hasNextLine())
{
String token = inputFile.nextLine();
System.out.println(token);
}
inputFile.close();
}
}