假设我想生成从 ArrayList 中获取的随机数:(1,2,3,4,5,6,7,8,9,10)
随机生成器生成 5。
列表更新 - AL:(1,2,3,4,6,7,8,9,10)
下一个随机数不能是5。
我正在编写一个从数组列表生成随机数的程序,一旦它生成随机数,列表就会删除该数字,并且下一个随机生成的数字不能是该数字。
ArrayList<Integer> numsLeft = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
Random randomGenerator = new Random();
int number = 0;
String cont;
do
{
number = randomGenerator.nextInt(numsLeft.size());
numsLeft.remove(number);
System.out.println (number + " continue (y/n)");
cont = (stdin.readLine());
}
while (cont.equalsIgnoreCase("y"));
但我在这里唯一能做的就是减小尺寸......
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
最佳答案
更简单的方法是简单地打乱您的列表,然后使用打乱后的顺序中的数字:
List<Integer> nums = new ArrayList<Integer>();
for (int i = 1; i < 11; i++)
nums.add(i);
Collections.shuffle(nums);
现在它们的顺序是随机的,只需一个一个地使用它们:
for (Integer i : nums) {
// use i
}
关于Java如何添加一个排除特定数字的随机生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19910128/