产生在java中唯一的随机数 [英] Generating unique random number in java
本文介绍了产生在java中唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要生成随机数从1到9,我想他们是唯一的。这是code我写这给了我1 9个不同的号码9,但我有生成唯一的号码毫无头绪。
int数据[] =新INT [10];
的for(int i = 0; I< data.length;我++){
随机randomGenerator =新的随机(); 数据[I] = randomGenerator.nextInt(10);
的System.out.println(数据由[i]); }
解决方案
填写一个列表与LT;整数GT;列表
与1..9,然后:
Collections.shuffle(名单);
请注意,以填补10数组,你必须有一个重复。
I want to generate random number from 1 to 9 and i want them to be unique. This is the code i have written which gives me 9 different numbers from 1 to 9 but I have no clue on generating unique number.
int data[] = new int[10];
for(int i = 0; i < data.length; i++) {
Random randomGenerator = new Random();
data[i] = randomGenerator.nextInt(10);
System.out.println(data[i]);
}
解决方案
Fill a List<Integer> list
with 1..9 and then:
Collections.shuffle(list);
Note that to fill an array of 10, you'll have to have one duplicate.
这篇关于产生在java中唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文