-1

我不确定为什么,但代码在到达循环部分时停止。我等了 10 分钟……但仍然没有任何改变。这不是一个无限循环。

PrintWriter out = new PrintWriter(new File("CollectingTheData.txt"));
File dataCollection = new File("CollectingTheData.txt");
Scanner inF = new Scanner(dataCollection);

System.out.println("\nSimulating Trials Now...One Moment Please...");

RandomSquirels = (int)(Math.random() * 11 + 1);

while (RunCount <= TrialNumber) {
    while (RandomSquirels != 10) {
        out.println(RandomSquirels);
    }
    
    out.close();
    RunCount++;
}

while (inF.hasNextLine()) {
    NumRead = Integer.parseInt(inF.nextLine());
    SquirelTotal += NumRead;
    
}
inF.close();

CalculationsForAv = (double)SquirelTotal / (double)TrialNumber;

System.out.println("The results! \nThe Average Number of \nSquirels Observed until Observing a Fox Squirrel: " + CalculationsForAv);

我只包含了代码的相关部分。导入所有必要的内容并定义所有变量。

4

2 回答 2

2
while (RandomSquirels != 10) {
    out.println(RandomSquirels);
}

你永远不会RandomSquirels在一段时间内改变价值,我想你想做的是:

while (RandomSquirels != 10) {
    out.println(RandomSquirels);
    RandomSquirels = (int)(Math.random() * 11 + 1);
}

我还注意到你会out.close()在一段时间内运行,所以你会一遍又一遍地尝试关闭它......你不应该关闭一个流超过一次。

于 2020-10-30T00:00:18.060 回答
1

Java 是一种命令式语言。您似乎认为:

RandomSquirels = (int)(Math.random() * 11 + 1);

就像一个宏,你认为它的意思是:“每次我写RandomSquirels,假设我写了(int)(Math.random() * 11 + 1)这不是 java 的工作方式

这意味着:立即运行表达式(int)(Math.random() * 11 + 1)一次,并将 this 的结果分配给变量RandomSquirels

然后循环 while RandomSquirelsis not 10 并将其打印到文件中。永远,除了每 11 次运行一次,当值恰好解析为 10 时。

于 2020-10-30T00:10:31.273 回答