我有一个包含 3 个变量的列表:(a
,b
,c
)。如果满足某些条件,是否有办法从此列表中随机选择?比方说:
if(some variable=2)
{
pick one variable from the list
}
if(some variable=4)
{
pick 2 variables from the list
}
..
and here comes the tricky part
if(some variable=10)
{
pick 5 variables out of the list( here the variables can duplicate)
it can be something like this : a,a,a,b,b
}
我正在为 Android 使用 Java。
最佳答案
只需创建一个生成随机数并使用它从列表中获取元素的方法。从每个 if
语句中调用它,应该可以解决问题。类似的东西(这只是一个想法):
private Object random() {
Random random = new Random();
int index = random.nextInt(3);
return yourList.get(index);
}
关于java - 从列表中选择随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31694208/