在使用 while 循环模拟五分之一的机会时遇到问题

Having trouble with using a while loop for simulating a 1 in 5 chance

我在使用一个程序时遇到了问题,该程序旨在计算某人赢得比赛的机会,他们有五分之一的机会获胜。这是一个重复 1000 次的模拟。当前循环正确地迭代一次,但对于所有其他循环只向文件输出零,我不明白为什么。

import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
public static void main (String [ ] args) throws IOException
{
    //establishing scanner and variables
    Scanner in = new Scanner(System.in);
    int minimumTrials = 1000;
    int enteredTrials = 0;
    int won = 0;
    int triesToWin = 0;
    double totalTries = 0;
    int winningValue = 0;
    //establishes the number of trials and sais if it is less than 1000
    while(enteredTrials < minimumTrials)
    {
    System.out.println("Please enter a number of trials greater than 1000: ");
    enteredTrials = in.nextInt();
    if(enteredTrials >= minimumTrials)
    {
        System.out.println("You enetred " + enteredTrials + " trials.");
    }
    else
    {
        System.out.println("You entered an incorrect number of trials.");
    }
    }
    //establishes file to write to
    PrintWriter outFile = new PrintWriter(new File("prizeResults.txt"));
    //writes to these files the amount of tries it takes to get the prize 1000 times
    for (int loop = 1; loop <= enteredTrials; loop++)
    {
        while(won != 1)
        {
            winningValue = (int)((Math.random() * 5.0) + 1.0);
            if(winningValue == 1)
            {
                won ++;
                triesToWin ++;
            }
            else
            {
                triesToWin ++;
            }   
        }
        winningValue = 0; 
        outFile.println(triesToWin);
        triesToWin = 0;
    }//end of for loop
    outFile.close ( ); //close the file when finished
    //finds the average number of tries it took
    File fileName = new File("prizeResults.txt");
    Scanner inFile = new Scanner(fileName);
    while (inFile.hasNextInt())
    {
        totalTries = totalTries + inFile.nextInt();
    }
    double averageTries = totalTries/enteredTrials;
    //tells the user the average
    System.out.println("You would have to by an average of " + averageTries + " bottles to win.");
}//end of main method

}//class

结束

您没有将赢额重置为零。因此,在第一次之后,当您将 won 增加到 1 时,while 循环结束,然后在每个后续的 for 循环中,它跳过 while 循环并打印您设置回零的 triesToWin 值。

尝试添加

won = 0;

写入文件后。