我正在尝试编写代码,通过从 10 中选择一个随机数来模拟 1000 多次试验的蒙特卡洛方法,直到数字为 10,然后每次都会增加(观察到的松鼠数量)的计数器,直到随机数数字是 10;然后这个计数器将被打印到一个文件中。然而,这是通过在 in 中嵌套循环的 For 循环完成的,但程序似乎在此 For 循环中永远加载一次,并且即使使用了 close() 文件也保持空白。
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
import java.util.Random;
public class AnimalPopulation
{
public static void main(String[] args) throws IOException
{
//declare and initialize variables
Random randsquirrel = new Random();
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File ("squirreldata.txt"));
// User input
System.out.println("Welcome to the Fox Squirrel Simulator");
System.out.println("\n");
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000:");
int trialcounter = in.nextInt();
// Input does not match requirements
while (trialcounter <= 1000)
{
System.out.print("\n\n Please try again. Enter a number greater than 1000.");
System.out.println();
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000:");
trialcounter = in.nextInt();
}
System.out.println("\nsimulating trials now... one moment please ...");
// Experiment with ratio of 1/10 fox squirrels
int randomsquirrel = 0;
int totalsquirrels = 0;
for (int i = 1; i <= trialcounter; i++)
{
randomsquirrel = randsquirrel.nextInt(10)+1;
while (randomsquirrel != 10)
{
totalsquirrels++;
}
if (randomsquirrel == 10);
{
totalsquirrels++;
}
outFile.println(totalsquirrels);
}
忽然笑
德玛西亚99
相关分类