1 package com.jdk7.chapter3; 2 3 import java.util.Random; 4 5 /** 6 * java.util.Math.random()随机生成[0,1]的浮点数 7 * @author Administrator 8 * 9 */ 10 public class Random1 { 11 public static void main(String[] args) { 12 System.out.println("随机生成[0,1]的浮点数"+Math.random()); 13 System.out.println("随机生成[0,1]的浮点数"+Math.random()); 14 15 System.out.println("随机生成int类型的数: "+(new Random()).nextInt()); 16 System.out.println("随机生成[0,30]的int类型的数: "+(new Random()).nextInt(30)); 17 System.out.println("随机生成[5,30]的int类型的数: "+(5+(new Random()).nextInt(30))); 18 19 System.out.println("随机生成[0,1] float类型的数: "+(new Random()).nextFloat()); 20 System.out.println("随机生成float类型的数后转换为int类型: "+(int) ((new Random()).nextFloat()*100)); 21 22 System.out.println("随机生成long类型的数: "+(new Random()).nextLong()); 23 24 System.out.println("随机生成[0,1] double类型的数: "+(new Random()).nextDouble()); 25 26 System.out.println("随机生成gaussian类型的数: "+(new Random()).nextGaussian()); 27 28 System.out.println("随机生成boolean类型的数: "+(new Random()).nextBoolean()); 29 30 //声明Random对象后,如果随机数种子相同,则生成完全一致的随机数 31 Random r1 = new Random(20); 32 for(int i=0;i<5;i++){ 33 System.out.print("r1: "+r1.nextInt(20)+" "); 34 } 35 System.out.println(); 36 37 Random r2 = new Random(20); 38 for(int i=0;i<5;i++){ 39 System.out.print("r2: "+r2.nextInt(20)+" "); 40 } 41 System.out.println(); 42 } 43 } 44 45 执行结果: 46 随机生成[0,1]的浮点数0.7475166373371607 47 随机生成[0,1]的浮点数0.5828554127694848 48 随机生成int类型的数: -1617055350 49 随机生成[0,30]的int类型的数: 6 50 随机生成[5,30]的int类型的数: 12 51 随机生成[0,1] float类型的数: 0.08533013 52 随机生成float类型的数后转换为int类型: 68 53 随机生成long类型的数: -7518776773801746754 54 随机生成[0,1] double类型的数: 0.7550215139757701 55 随机生成gaussian类型的数: 0.04748439140005734 56 随机生成boolean类型的数: true 57 r1: 13 r1: 16 r1: 1 r1: 1 r1: 5 58 r2: 13 r2: 16 r2: 1 r2: 1 r2: 5