You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java模拟1/5中奖概率程序异常:仅首次循环有效其余输出0

问题分析与解决方案:抽奖模拟程序重复循环输出0的问题

我一眼就揪出了问题的核心——你在第一次模拟中奖后,won变量没有被重置为0!

咱们拆解下流程就能明白:

  1. 第一次外层for循环时,won初始是0,内层while(won != 1)正常执行,直到抽到中奖结果,won变成1,接着你把triesToWin写入文件并重置它。
  2. 但到了第二次外层循环,won还是1,内层的while(won != 1)条件直接不成立,循环根本不会运行,triesToWin保持0,所以写入文件的就是0,后面所有循环全是这个情况。

修正方案

只需要在每次外层for循环的开头,把won重置为0就行。另外我还帮你优化了平均值计算的逻辑——不用写完文件再读回来,直接在模拟过程中累加总次数,省掉一次IO操作,效率更高。

修正后的完整代码:

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 {
        // 初始化输入和变量
        Scanner in = new Scanner(System.in);
        final int minimumTrials = 1000;
        int enteredTrials = 0;
        int won = 0;
        int triesToWin = 0;
        double totalTries = 0;

        // 获取符合要求的试验次数
        while (enteredTrials < minimumTrials) {
            System.out.println("Please enter a number of trials greater than or equal to 1000: ");
            enteredTrials = in.nextInt();
            if (enteredTrials >= minimumTrials) {
                System.out.println("You entered " + enteredTrials + " trials.");
            } else {
                System.out.println("You entered an incorrect number of trials.");
            }
        }

        // 准备输出文件
        PrintWriter outFile = new PrintWriter(new File("prizeResults.txt"));

        // 模拟每次试验:直到中奖为止的尝试次数
        for (int loop = 1; loop <= enteredTrials; loop++) {
            // 关键:每次试验开始前重置中奖状态
            won = 0;
            triesToWin = 0;
            while (won != 1) {
                // 生成1-5的随机数,1代表中奖
                int winningValue = (int) ((Math.random() * 5.0) + 1.0);
                triesToWin++;
                if (winningValue == 1) {
                    won = 1;
                }
            }
            outFile.println(triesToWin);
            // 直接累加总次数,不用后续读文件
            totalTries += triesToWin;
        }

        outFile.close();
        in.close();

        // 计算并输出平均值
        double averageTries = totalTries / enteredTrials;
        System.out.println("You would have to buy an average of " + averageTries + " bottles to win.");
    }
}

额外优化说明

  • 把winningValue的定义移到了内层循环里,符合局部变量的使用规范,避免不必要的全局变量。
  • 优化了变量命名和注释,让代码可读性更好。
  • 最后关闭了输入Scanner,避免资源泄漏。

内容的提问来源于stack exchange,提问作者CH00CH00CHARLIE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:39