可能的重复:
Java:生成一定范围内的随机数 https://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range
如何生成两个数字之间的随机值。Random.nextInt() http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int)给你 0 和传递的值之间的值。如何生成 minValue 和 maxValue 之间的值
写一个方法,如:
public static int getRandom(int from, int to) {
if (from < to)
return from + new Random().nextInt(Math.abs(to - from));
return from - new Random().nextInt(Math.abs(to - from));
}
这也考虑到了事实,即nextInt()
论证必须是积极的,并且from那么可以更大to.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)