java生成随机数总结
2013-11-27 23:16
393 查看
import java.util.*; public class RandomDemo{ public static void main(String[] args){ /* Math.random()的随机数范围为0<=n<1,即:[0,1) */ double d1 = Math.random(); System.out.println(d1); /* 0.13588173801188785 */ /* 生成4位随机整数 */ int i4 = (int)(Math.random()*9000)+1000; System.out.println(i4); /* 6287 */ /* Math取整数的几个方法说明: Math.floor 向下取整(不大于参数的最大整数 ) Math.ceil 向上取整(不小于参数的最大整数 ) math.round 四舍五入取整(算法为Math.floor(x+0.5)) */ System.out.println(Math.floor(2.5)); System.out.println(Math.floor(-2.5)); System.out.println(Math.ceil(2.5)); System.out.println(Math.ceil(-2.5)); System.out.println(Math.round(2.5)); System.out.println(Math.round(-2.5)); /* 2.0 -3.0 3.0 -2.0 3 -2 */ Random r = new Random(); /* public boolean nextBoolean(); 随机数范围为:false、true */ boolean b1 = r.nextBoolean(); System.out.println(b1); /* false */ /* public int nextInt(); 随机数范围为: int的区间 */ int i1 = r.nextInt(); System.out.println(i1); /* -1098866320 */ /* public long nextLong(); 随机数范围为: long的区间 */ long l1 = r.nextLong(); System.out.println(l1); /* 8115353135541459577 */ /* public int nextInt(int n); 随机数范围为:[0,n) */ int i2 = r.nextInt(100); System.out.println(i2); /* 71 */ /* public float nextFloat(); 随机数范围为:[0,1) */ float f1 = r.nextFloat(); System.out.println(f1); /* 0.42610747 */ /* public double nextDouble(); 随机数范围为:[0,1) */ double d2 = r.nextDouble(); System.out.println(d2); /* 0.28172834985842776 */ /* public void setSeed(long seed) 设置在种子数的基础上进行一定的变换产生随机数。 相同种子数的Random对象,相同次数生成的随机数字是完全相同的。即第1次生成的随机数相同 ,第2次生成的随机数也相同,......,第n次生成的随机数也相同。 */ Date date = new Date(); long time = date.getTime(); Random r2 = new Random(); Random r3 = new Random(); r2.setSeed(time); r3.setSeed(time); int i21 = r2.nextInt(100); int i22 = r2.nextInt(100); int i23 = r2.nextInt(100); int i31 = r3.nextInt(100); int i32 = r3.nextInt(100); int i33 = r3.nextInt(100); System.out.println(i21 + " " + i22 + " " + i23); System.out.println(i31 + " " + i32 + " " + i33); /* 96 57 5 96 57 5 */ } }
相关文章推荐
- java中随机数的生成总结
- Java中生成随机数的实现方法总结
- JAVA 时间戳+随机数生成唯一ID
- Java生成随机数的2种示例方法代码
- (一)JAVA生成随机数工具类RandomStringUtils详解
- java实现和电脑猜随机数生成1到100
- java生成两数之间随机数实例
- Java生成随机数
- (二)java生成随机数工具类RandomUtils详解
- Java 随机数总结
- 数字加大小写字母随机数的生成 js java
- java生成N位随机数
- java生成6位随机数的5种方法
- Java随机生成指定区间的随机数
- java 随机数生成工具类
- Java记录 -39- 生成指定范围内随机数
- JAVA生成随机数(生成给定范围内N个不重复数)
- Java 生成随机数
- MATLAB生成随机数总结
- Java中随机数生成的两种方法,以及math的floor