我从1到100生成了一个随机数,但不会出现重复的数字(例如,如果10出现一个,那么它将不再出现)。(这不起作用)
final Random random = new Random();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while (arrayList.size() < 6) { // how many numbers u need - it will 6
int a = random.nextInt(91)+1; // this will give numbers between 1 and 90.
if (!arrayList.contains(a)) {
arrayList.add(a);
}
}
以及如何使用生成的数字出现在屏幕底部,以便用户必须知道要完成的数字如果1-100全部完成了,则不会生成数字
谁能帮我这个
试试这个可能对你有帮助
Random rng = new Random(); // Ideally just create one instance globally
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < numbersNeeded; i++)
{
while(true)
{
Integer next = rng.nextInt(max) + 1;
if (!generated.contains(next))
{
// Done for this iteration
generated.add(next);
break;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句