很久没写随机数了,忘记了怎么写,百度了下,把结果记录下来。
方法一:
直接使用Math.random()这个静态的方法,random()方法返回一个[0,1)的随机数;
方法二:
使用java.util.Random类,创建一个实例,使用nextInt(int count)获得count以内的整数,不含count
下面是获取十个0-20不重复随机数的实例:
HashSet<Integer> hs = new HashSet<Integer>();
Random random = new Random();
while (hs.size() < 10){
hs.add(random.nextInt(21));
}
System.out.println(hs);