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

Java生成随机数统计命中指定值次数的代码优化问询

优化方案

你可以将随机数赋值逻辑整合到while循环的条件判断中,仅保留一处随机范围配置,运行效果和原有代码完全一致:

Random r = new Random();
int o = 0;
int x;

// 随机数生成仅写一次,赋值后直接判断是否满足终止条件
while ((x = r.nextInt(50) + 1) != 15) {
    o++;
    System.out.println("Try number: " + o + " and random number is: " + x);
}

System.out.println("The answer is 15!");

优化说明

  • 完全消除了重复的随机数生成代码,后续调整随机数范围只需要修改r.nextInt(50) + 1这一处即可,避免漏改导致逻辑异常
  • 代码逻辑更紧凑,减少了不必要的前置变量初始化操作

如果需要更高的可维护性,还可以把目标值、随机数范围抽为常量,后续修改需求不用翻业务逻辑:

Random r = new Random();
final int RANDOM_UPPER = 50; // 随机数上限
final int TARGET_NUM = 15; // 目标命中值
int attemptCount = 0;
int randomNum;

while ((randomNum = r.nextInt(RANDOM_UPPER) + 1) != TARGET_NUM) {
    attemptCount++;
    System.out.println("Try number: " + attemptCount + " and random number is: " + randomNum);
}

System.out.println("The answer is " + TARGET_NUM + "!");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:54:01