【发布时间】:2015-06-22 12:12:45
【问题描述】:
我很难确保下面的代码中没有重复的数字。我尝试创建一个 ArrayList 来添加数组的所有可能索引,然后随着数字生成器生成更多元素,逐渐从 List 中删除数组的值。这;但是,没有像我预期的那样工作。我一直在尝试考虑它,但还没有提出可行的解决方案。
Random randGen = new Random();
public boolean onTouchEvent(MotionEvent touchevent) {
switch (touchevent.getAction()) {
case MotionEvent.ACTION_DOWN: {
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP: {
x2 = touchevent.getX();
y2 = touchevent.getY();
int maxLength=exampleArray.length;
List<Integer>indices=new ArrayList<Integer>(maxLength);
for(int i=0;i<maxLength;i++){
indices.add(i);
}
int randomApple = randGen.nextInt(exampleArray.length);
int randomNum=indices.get(randomApple) ;
indices.remove(randomApple);
textView.setText(exampleArray[randomNum]);
if (x1 < x2) {
}
if (x1 > x2) {
//textView.setText(exampleArray[randomNum]);
}
}
}
return false;
}
【问题讨论】:
-
请参阅this answer,了解在不同情况下生成非重复随机数的三种方法。
-
我喜欢每个人的答案,但我很好奇为什么我认为正确的解决方案不起作用
-
您正在为每个
ACTION-UP生成一个全新的indices列表。如果您不想跨不同事件重复,那么您将必须在不同事件中存储已使用或未使用的数字,以避免跨事件重复。 -
我想我明白你的意思了。谢谢你的建议。您说每次使用 ACTION_UP 时,都会使用一个新的索引列表,对吗?为了纠正这个问题,您是否建议将索引列表移至全球?
标签: android arrays random textview generator