java随机数生成_java随机数生成器

packagecom.random;importjava.util.Random;importorg.junit.After;importorg.junit.Assert;importorg.junit.BeforeClass;importorg.junit.Ignore;importorg.junit.Test;public classtestRandom {private staticRandom r1;private staticRandom r2;/*** @Title: loadUp

* @Description: 测试之前的初始化工作*/@BeforeClasspublic static voidloadUp() {

r1= new Random(10);

r2= new Random(10);

}

@Afterpublic voidtestAfter() {

System.out.println("------------------------>");

}/*** @Title: testMathRandom

* @Description: 通过Math.random产生[0,5)之间的数

*@throws

*/@Ignore

@Testpublic voidtestMathRandom() {for (int i = 0; i < 20; i++) {

System.out.println((int) (Math.random() * 5));

}

}/*** @Title: testTwoRandom

* @Description: 两个random对象,具有相同的种子,会产生相同的随机数(伪随机)*/@Testpublic voidtestTwoRandom() {for (int i = 0; i < 10; ++i) {

Assert.assertEquals(r1.nextInt(), r2.nextInt());

}

}/*** @Title: testRandom1

* @Description: 产生[1,2.5)之间的数的,有公式 nextDouble()*(b-a)+a

*@param设定文件

*@returnvoid 返回类型

*@throws

*/@Test

@Ignorepublic voidtestRandom1() {for (int i = 0; i < 10; ++i) {

System.out.println(r1.nextDouble()* 1.5 + 1);

}

}/*** @Title: testRandom2

* @Description: 产生[0,10)的两种方法,生成[0,n)区间的数有公式Math.abs(nextInt()%n)和nextInt(n)*/@Test

@Ignorepublic voidtestRandom2() {for (int i = 0; i < 10; ++i) {

System.out.println("方法一: " + r1.nextInt(10));

System.out.println("方法二: " + Math.abs(r2.nextInt() % 10));

}

}/*** @Title: testNextBoolean

* @Description: 生成一个随机的boolean值,true和false值均等*/@Test

@Ignorepublic voidtestNextBoolean() {for (int i = 0; i < 10; ++i) {

System.out.println(r1.nextBoolean());

}

}/*** @Title: testNextInt

* @Description: 生成一个-2^31~2^31-1之间的随机数*/@Test

@Ignorepublic voidtestNextInt() {for (int i = 0; i < 10; ++i) {

System.out.println(Math.abs(r1.nextInt()));//0~2^31-1

System.out.println(r1.nextInt());//-2^31~2^31-1

System.out.println(r1.nextInt(10));//[0,10),参数10为随机生成数字的上限

}

}/*** @Title: testNextDouble

* @Description: 随机生成[0,1.0)区间的小数*/@Test

@Ignorepublic voidtestNextDouble() {for (int i = 0; i < 10; ++i) {

System.out.println(r1.nextDouble());

}

}/*** @Title: testRandom3

* @Description: 生成任意区间[a,b),公式nextInt(b-a)+a和Math.abs(nextInt()%(b-a)+a),例如区间[-3,15)*/@Test

@Ignorepublic voidtestRandom3() {for (int i = 0; i < 100; ++i) {

System.out.println(r1.nextInt(18) - 3);

System.out.println(Math.abs(r1.nextInt()%18)-3);

}

}/*** @Title: testRandom4

* @Description: 生成任意区间[a,b],公式nextInt(b+1-a)+a和Math.abs(nextInt()%(b+1-a)+a),例如区间[3,10]*/@Testpublic voidtestRandom4(){for(int i=0;i<20;++i){

System.out.println(r1.nextInt(8)+3);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值