[英]Picking a random element from an arraylist and removing it from the list in Java
[英]Picking out a random element from an organised ArrayList
所以这里的想法是,我有一个带有一组单词的ArrayList,我想对列表进行排序,以便它只包括带有偶数编号的索引的条目,然后随机选择一个条目。 我给了它一个bash,我设法使其仅显示如下所示的奇数项:
int i = 0;
for (Iterator<Phrase> it = phrases.iterator(); it.hasNext(); i++)
{
Phrase current = it.next();
if (i % 2 == 0)
{
System.out.println(current);
}
}
并且这会打印出ArrayList上的每个奇数元素,这很好,但是我不知道如何从奇数元素中随机选择一个。 这是我尝试放入if语句中的内容,但没有达到我想要的效果,它会随机打印出元素,但是当我只需要偶数元素时,它还会包含奇数元素
Random r = new Random();
int x = r.nextInt(phrases.size());
System.out.println(phrases.get(x));
在这里,任何帮助将不胜感激,谢谢。
但我不知道如何从奇数中随机选择一个。
如何确保x
为大小的一半并将其乘以2
以获得偶数索引呢? 请尝试以下操作:
Random r = new Random();
int x = r.nextInt(phrases.size()/2) + (list.size() & 1) - 1;
// size is divided by 2
// so that x is randomly 0 to (size/2 -1) inclusive
System.out.println(phrases.get(x * 2)); // ensuring the accessing index are even
您可以循环直到获得一个,但从技术上讲,这可能永远不会发生。 因此,只需确保x是2的倍数即可。
Random r = new Random();
int x = r.nextInt(phrases.size()); // Might be even or odd
x = x % 2 != 0 ? x + 1 : x; // if x is not divisible by 2, x + 1, else x
// x is is now a multiple of two
if(x >= phrases.size()){ // make sure x is still within the
// index boundaries.
x = x-2;
if(x < 0){
x = 0;
}
}
System.out.println(phrases.get(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.