在我的 Android 应用程序中,我需要从指定范围内选择两个随机整数。下面的代码有效,但它并不是真正选择一个随机整数,而是对整数进行洗牌。randomNum2= (int)it.next();
让我烦恼的是,由于代码中的位,我必须将最大 int 指定为实际上比最大值小一。如果我将正确的数字(当前为 127)作为最大值,那么我会收到错误java.util.NoSuchElementException
,因为它正在寻找 128 作为下一次迭代。在我使用之前rand = new Random();
randomNum1 = rand.nextInt(max - min + 1) + min;
randomNum2 = rand.nextInt(max - min + 1) + min;
但问题是两个随机整数最终可能相同,我需要它们是唯一的。那么任何人都可以提出一种更好的方法来从最小/最大整数范围中获取两个随机数吗?这是我的代码:
int min = 1;
int max = 126;
int randomNum1;
int randomNum2;
List<Integer> choicesL;
public void randomTwo() {
choicesL = new LinkedList<Integer>();
for (int i = min; i <= max; i++) {
choicesL.add(i);
}
Collections.shuffle(choicesL);
Iterator<Integer> it = choicesL.iterator();
while (it.hasNext())
{
randomNum1= (int)it.next();
randomNum2= (int)it.next();
}
}