Random类有参构造和无参构造的区别
构造方法
public Random();//没有给种子,用的是默认种子,默认当前时间的毫秒值
public Random(long seed);//给定指定的种子
- 区别:给定种子后,每次生成的随机数是相同的
成员方法
public int nextInt();//生成int范围内的随机数
public int nextInt(int n);//生成[0,n)范围内的随机数
举例1(无参构造):
public class RandomDemo {
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int nextInt = random.nextInt();
System.out.print(nextInt+" ");
}
}
}
第一次运行结果 -1363259557 -659261602 532517386 602344502 2026559144 -1996656533 -1703428110 -293368139 -1684676521 -318137087
第二次运行结果 191758384 188671421 -875799977 1838099674 -122532721 -719586295 -1715817218 -49835181 -1023140276 1660139763
第二次运行结果 974463230 -1605132646 3374635 1440703910 1524629612 1934123605 48675377 -924506726 701025884 -419035815
举例2(有参构造):
public class RandomDemo {
public static void main(String[] args) {
Random random = new Random(1000);
for (int i = 0; i < 10; i++) {
int nextInt = random.nextInt(100);
System.out.print(nextInt+" ");
}
}
}
第一次运行结果 87 35 76 24 92 49 41 45 64 50
第二次运行结果 87 35 76 24 92 49 41 45 64 50
第三次运行结果 87 35 76 24 92 49 41 45 64 50