《java入门第一季》之Random类和获取随机数案例

/*
 * Random:产生随机数的类
 * 
 * 构造方法:
 * public Random():没有给种子,用的是默认种子,是当前时间的毫秒值下的随机数,所以会一直变化
 * public Random(long seed):给出指定的种子    long  seed就是一个long类型的数据而已

 * 给定种子后,每次得到的随机数是(相同的)。再次编译执行后的数据不变了。

*              种子是什么,又怎么变与不变?根据例子说明。

*/

public class RandomDemo {
	public static void main(String[] args) {
		// 创建对象
		Random r1 = new Random();//没给种子
		Random r = new Random(111);//long 给的种子不同

		//随机获取10个1-100的随机数
		for (int x = 0; x < 10; x++) {
			// int num = r.nextInt();
			int num = r.nextInt(100) + 1;
			System.out.println(num);
		}
		System.out.println("--------------------------");
		for(int x = 0; x < 10; x++){
			int num = r1.nextInt(100) + 1;
			System.out.println(num);
		}
	}
}

输出结果:

294
971
958
698
410
921
285
613
598
966
--------------------------
857
683
744
768
282
613
23
743
763
414


再一次编译输出结果:

294
971
958
698
410
921
285
613
598
966
--------------------------
751
924
654
376
20
95
563
576
43
108

这个时候什么是种子,什么是不变与变化的区别一目了然了吧。


同时,利用Random获取1-100的另一种方式也已经完成了。即上面的几行代码:

for (int x = 0; x < 10; x++) {
			// int num = r.nextInt();
			int num = r.nextInt(100) + 1;
			System.out.println(num);
		}

转载于:https://www.cnblogs.com/wanghang/p/6299812.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值