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
相关产品推荐
相关产品推荐

