【发布时间】: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 example 和 How to Debug Small Programs
-
抱歉不清楚输出预期的输出将是一个大于一的整数,表示平均尝试掷一次的次数。
-
我没有要求你澄清输出。我让你澄清你做了什么调试。就目前而言,这个问题似乎没有显示出您的任何努力,并且对未来的读者没有帮助。请edit您的问题来解决这些问题,并且可能会撤回反对票。
标签: java random simulation