getNormalList函数重复数字检查失效:为何仍返回三个相同随机数?
问题原因分析
哦,这个问题我太熟悉啦!你当前的代码只做了一次补救性的重新生成,这就是为什么偶尔还是会出现三个相同数字的原因。
咱们拆解下逻辑:
- 第一次生成3个随机数,如果刚好三个都相同,你会清空列表再生成一次新的。
- 但问题来了:这次重新生成的结果依然有可能碰巧又是三个相同的(虽然概率低,但架不住随机啊!),而这时候代码没有再次检查,直接就把这个不符合要求的列表返回了。
举个例子:第一次生成[4,4,4],触发if条件,重新生成;结果运气不好,又生成了[2,2,2],这时候代码不会再做检查,直接返回这个列表,自然就不符合你的预期了。
解决方案:循环验证直到符合要求
解决思路很简单:不要只检查一次,而是循环生成,直到得到符合条件的列表为止。用do-while循环是最适合的,因为它会先执行一次生成逻辑,再判断是否需要重复执行。
修改后的代码如下:
public class SpinResultGenerator { // 把Random作为类成员变量,避免每次调用都创建,提升随机数均匀性 private Random r = new Random(); public ArrayList<Integer> getNormalList() { ArrayList<Integer> integerList = new ArrayList<Integer>(); int Low = 0; int High = 6; do { integerList.clear(); for (int i = 0; i < 3; i++) { int number = r.nextInt(High - Low) + Low; integerList.add(number); } // 只要三个数字完全相同,就重新生成 } while (integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)); return integerList; } public ArrayList<Integer> getJackpotList() { ArrayList<Integer> integerList = new ArrayList<Integer>(); integerList.add(5); integerList.add(5); integerList.add(5); return integerList; } }
额外优化小提示
- 把
Random实例提升为类的成员变量,而不是每次调用getNormalList()都新建一个。频繁创建Random可能会因为系统时间种子的问题,导致生成的随机数不够均匀。 - 你的原判断里
integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)已经足够判断三个数字是否完全相同了,不需要再加integerList.get(1) == integerList.get(2),因为前两个条件已经能推导出第三个啦。
内容的提问来源于stack exchange,提问作者BozZ
相关产品推荐
相关产品推荐

