说明:编写一个使用蒙特卡罗抽样方法进行估算的程序 有人必须喝的电子Boost的平均瓶数 赢了一个奖。瓶盖有五分之一的机会获得奖品。
编辑:
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
public static void main(String args[]) throws IOException
{
PrintWriter outFile = new PrintWriter(new File("bottleCap.txt"));
Scanner input = new Scanner (System.in);
int counter = 0;
int winCounter = 0;
Random randNum = new Random();
int randNumber = randNum.nextInt(5) + 1;
System.out.print("How many trails would you like to do?");
int trials = input.nextInt();
while(trials != 1)
{
//Random randNum = new Random();
randNumber = randNum.nextInt(5) + 1;
while(randNumber != 1)
{
if(randNumber != 1)
{
//System.out.println("You don't win");
}
else if(randNumber == 1)
{
winCounter++;
outFile.println(counter);
System.out.println("You win in " + counter + " bottles");
winCounter++;
//System.out.println("counter: " + counter + "\tWin counter: " + winCounter);
}
counter++;
}
}
outFile.close();
}
}
答案 0 :(得分:0)
(此答案正在将the comments under the question转换为正式答案)
当您使用构造
时,您正在经历无限(无限)循环while(trials != 1)
但从未将trials
设为1
。
如果你想让循环执行10次,你应该使用for循环和一个计数器(我注意到你已经有一个计数器,你在每次迭代都递增,但本身没有被引用)。
使用以下结构的for循环应该有助于替换上面引用的行while(trials != 1)
for (int counter = 0; counter < 10; counter++)