【问题标题】:Having trouble with using a while loop for simulating a 1 in 5 chance使用 while 循环模拟五分之一的机会时遇到问题
【发布时间】:2025-12-07 08:15:02
【问题描述】:

我在使用一个程序来计算某人赢得比赛的机会时遇到了问题,他们有五分之一的获胜机会。这是一个重复 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

}//课程结束

【问题讨论】:

  • 我对这个问题投了反对票,因为没有证据表明对此代码执行了任何调试。请edit您的问题向我们展示您的调试发现了什么,以及关于特定代码行的特定问题。请参阅:How to create a Minimal, Complete, and Verifiable exampleHow to Debug Small Programs
  • 抱歉不清楚输出预期的输出将是一个大于一的整数,表示平均尝试掷一次的次数。
  • 我没有要求你澄清输出。我让你澄清你做了什么调试。就目前而言,这个问题似乎没有显示出您的任何努力,并且对未来的读者没有帮助。请edit您的问题来解决这些问题,并且可能会撤回反对票。

标签: java random simulation


【解决方案1】:

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

尝试添加

赢了 = 0;

写入文件后。

【讨论】:

  • 是的,我昨天意识到了这一点,忘了更新,但你完全正确。
最近更新 更多