一、常用方法
使用Random时需要导入java.util.Random
1、nextInt()
返回一个小于2^32的整数;
2、nextInt(int n)
返回一个大于等于0小于n的整数;
3、nextFloat()
返回一个0到1.0之间的float类型数;
4、nextDouble()
返回一个0到1.0之间的double类型数。
5、nextBoolean()
返回一个true或false
import java.util.Random;
public class text{
public static void main(String[] args) {
Random rand=new Random();
System.out.println(rand.nextBoolean());
System.out.println(rand.nextDouble());
System.out.println(rand.nextInt());
System.out.println(rand.nextInt(10));
System.out.println(rand.nextFloat());
}
}
结果:
false
0.07458262019718465
1598785303
3
0.5371009
二、产生10个0到10之间不重复的随机数
利用boolean类型的数组判断产生的随机数位置上是否为true,为true代表该数已经存在。
import java.util.ArrayList;
import java.util.Random;
public class text{
public static void main(String[] args) {
int index;
Random rand=new Random();
ArrayList<Integer> list=new ArrayList<Integer>();
boolean a[]=new boolean[10];
for(int i=0;i<10;i++) {
do {
index=rand.nextInt(10);
}while(a[index]);
a[index]=true;
list.add(index);
}
System.out.println(list);
}
}
结果:
[0, 4, 8, 2, 9, 3, 6, 5, 7, 1]