zoukankan      html  css  js  c++  java
  • java产生随机数的三种方式

    转自:https://blog.csdn.net/YTTmiao/article/details/78187448

    随机数在实际中使用很广泛,比如要随即生成一个固定长度的字符串、数字。或者随即生成一个不定长度的数字、或者进行一个模拟的随机选择等等。Java提供了最基本的工具,可以帮助开发者来实现这一切。

        一、Java随机数的产生方式

        在Java中,随机数的概念从广义上将,有三种。

        1、通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字。

        2、通过Math.random()返回一个0到1之间的double值。

        3、通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大。

        二、Random类API说明

        1、Java API说明

        Random类的实例用于生成伪随机数流。此类使用 48 位的种子,使用线性同余公式对其进行修改(请参阅 Donald Knuth 的《The Art of Computer Programming, Volume 2》,第 3.2.1 节)。

        如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。为了保证属性的实现,为类 Random 指定了特定的算法。

        很多应用程序会发现 Math 类中的 random 方法更易于使用。

        2、方法摘要

    [html] view plain copy
     
    1. Random()   
    2.           创建一个新的随机数生成器。   
    3. Random(long seed)   
    4.           使用单个 long 种子创建一个新随机数生成器: public Random(long seed) { setSeed(seed); } next 方法使用它来保存随机数生成器的状态。  
    5.    
    6. protected  int next(int bits)   
    7.           生成下一个伪随机数。   
    8.  boolean nextBoolean()   
    9.           返回下一个伪随机数,它是从此随机数生成器的序列中取出的、均匀分布的 boolean 值。   
    10.  void nextBytes(byte[] bytes)   
    11.           生成随机字节并将其置于用户提供的字节数组中。   
    12.  double nextDouble()   
    13.           返回下一个伪随机数,它是从此随机数生成器的序列中取出的、在 0.0 和 1.0之间均匀分布的 double 值。   
    14.  float nextFloat()   
    15.           返回下一个伪随机数,它是从此随机数生成器的序列中取出的、在 0.0 和 1.0 之间均匀分布的 float 值。   
    16.  double nextGaussian()   
    17.           返回下一个伪随机数,它是从此随机数生成器的序列中取出的、呈高斯(“正常地”)分布的 double 值,其平均值是 0.0,标准偏差是 1.0。   
    18.  int nextInt()   
    19.           返回下一个伪随机数,它是此随机数生成器的序列中均匀分布的 int 值。   
    20.  int nextInt(int n)   
    21.           返回一个伪随机数,它是从此随机数生成器的序列中取出的、在 0(包括)和指定值(不包括)之间均匀分布的 int值。   
    22.  long nextLong()   
    23.           返回下一个伪随机数,它是从此随机数生成器的序列中取出的、均匀分布的 long 值。   
    24.  void setSeed(long seed)   
    25.           使用单个 long 种子设置此随机数生成器的种子。  

    三、Random类使用说明

        1、带种子与不带种子的区别Random类使用的根本是策略分带种子和不带种子的Random的实例。

        通俗说,两者的区别是:带种子的,每次运行生成的结果都是一样的。

        不带种子的,每次运行生成的都是随机的,没有规律可言。

        2、创建不带种子的Random对象

        Random random = new Random();

        3、创建不带种子的Random对象有两种方法:

        1) Random random = new Random(555L);

        2) Random random = new Random();random.setSeed(555L);

        四、测试

        通过一个例子说明上面的用法

    [html] view plain copy
     
    1. import java.util.Random;   
    2.   
    3.   
    4. public class TestRandomNum {   
    5.         public static void main(String[] args) {   
    6.                 randomTest();   
    7.                 testNoSeed();   
    8.                 testSeed1();   
    9.                 testSeed2();   
    10.         }   
    11.   
    12.         public static void randomTest() {   
    13.                 System.out.println("--------------test()--------------");   
    14.                 //返回以毫秒为单位的当前时间。   
    15.                 long r1 = System.currentTimeMillis();   
    16.                 //返回带正号的 double 值,大于或等于 0.0,小于 1.0。   
    17.                 double r2 = Math.random();   
    18.                 //通过Random类来获取下一个随机的整数   
    19.                 int r3 = new Random().nextInt();   
    20.                 System.out.println("r1 = " + r1);   
    21.                 System.out.println("r3 = " + r2);   
    22.                 System.out.println("r2 = " + r3);   
    23.         }   
    24.   
    25.         public static void testNoSeed() {   
    26.                 System.out.println("--------------testNoSeed()--------------");   
    27.                 //创建不带种子的测试Random对象   
    28.                 Random random = new Random();   
    29.                 for (int i = 0; i 3; i++) {   
    30.                         System.out.println(random.nextInt());   
    31.                 }   
    32.         }   
    33.   
    34.         public static void testSeed1() {   
    35.                 System.out.println("--------------testSeed1()--------------");   
    36.                 //创建带种子的测试Random对象   
    37.                 Random random = new Random(555L);   
    38.                 for (int i = 0; i 3; i++) {   
    39.                         System.out.println(random.nextInt());   
    40.                 }   
    41.         }   
    42.   
    43.         public static void testSeed2() {   
    44.                 System.out.println("--------------testSeed2()--------------");   
    45.                 //创建带种子的测试Random对象   
    46.                 Random random = new Random();   
    47.                 random.setSeed(555L);   
    48.                 for (int i = 0; i 3; i++) {   
    49.                         System.out.println(random.nextInt());   
    50.                 }   
    51.         }   
    52. }  

     运行结果:

    [java] view plain copy
     
    1. --------------test()--------------   
    2. r1 = 1227108626582   
    3. r3 = 0.5324887850155043   
    4. r2 = -368083737   
    5. --------------testNoSeed()--------------   
    6. 809503475   
    7. 1585541532   
    8. -645134204   
    9. --------------testSeed1()--------------   
    10. -1367481220   
    11. 292886146   
    12. -1462441651   
    13. --------------testSeed2()--------------   
    14. -1367481220   
    15. 292886146   
    16. -1462441651   
    17.   
    18. Process finished with exit code 0  

    通过testSeed1()与testSeed2()方法的结果可以看到,两个打印结果相同,因为他们种子相同,再运行一次,结果还是一样的,这就是带种子随机数的特性。

        而不带种子的,每次运行结果都是随机的。

    五、综合应用

        下面通过最近写的一个随机数工具类来展示用法:

    [java] view plain copy
     
    1. import java.util.Random;   
    2.   
    3. /**  
    4. * 随机数、随即字符串工具  
    5. */   
    6. public class RandomUtils {   
    7.         public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";   
    8.         public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";   
    9.         public static final String numberChar = "0123456789";   
    10.   
    11.         /**  
    12.          * 返回一个定长的随机字符串(只包含大小写字母、数字)  
    13.          *  
    14.          * @param length 随机字符串长度  
    15.          * @return 随机字符串  
    16.          */   
    17.         public static String generateString(int length) {   
    18.                 StringBuffer sb = new StringBuffer();   
    19.                 Random random = new Random();   
    20.                 for (int i = 0; i < length; i++) {   
    21.                         sb.append(allChar.charAt(random.nextInt(allChar.length())));   
    22.                 }   
    23.                 return sb.toString();   
    24.         }   
    25.   
    26.         /**  
    27.          * 返回一个定长的随机纯字母字符串(只包含大小写字母)  
    28.          *  
    29.          * @param length 随机字符串长度  
    30.          * @return 随机字符串  
    31.          */   
    32.         public static String generateMixString(int length) {   
    33.                 StringBuffer sb = new StringBuffer();   
    34.                 Random random = new Random();   
    35.                 for (int i = 0; i < length; i++) {   
    36.                         sb.append(allChar.charAt(random.nextInt(letterChar.length())));   
    37.                 }   
    38.                 return sb.toString();   
    39.         }   
    40.   
    41.         /**  
    42.          * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)  
    43.          *  
    44.          * @param length 随机字符串长度  
    45.          * @return 随机字符串  
    46.          */   
    47.         public static String generateLowerString(int length) {   
    48.                 return generateMixString(length).toLowerCase();   
    49.         }   
    50.   
    51.         /**  
    52.          * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)  
    53.          *  
    54.          * @param length 随机字符串长度  
    55.          * @return 随机字符串  
    56.          */   
    57.         public static String generateUpperString(int length) {   
    58.                 return generateMixString(length).toUpperCase();   
    59.         }   
    60.   
    61.         /**  
    62.          * 生成一个定长的纯0字符串  
    63.          *  
    64.          * @param length 字符串长度  
    65.          * @return 纯0字符串  
    66.          */   
    67.         public static String generateZeroString(int length) {   
    68.                 StringBuffer sb = new StringBuffer();   
    69.                 for (int i = 0; i < length; i++) {   
    70.                         sb.append('0');   
    71.                 }   
    72.                 return sb.toString();   
    73.         }   
    74.   
    75.         /**  
    76.          * 根据数字生成一个定长的字符串,长度不够前面补0  
    77.          *  
    78.          * @param num             数字  
    79.          * @param fixdlenth 字符串长度  
    80.          * @return 定长的字符串  
    81.          */   
    82.         public static String toFixdLengthString(long num, int fixdlenth) {   
    83.                 StringBuffer sb = new StringBuffer();   
    84.                 String strNum = String.valueOf(num);   
    85.                 if (fixdlenth - strNum.length() >= 0) {   
    86.                         sb.append(generateZeroString(fixdlenth - strNum.length()));   
    87.                 } else {   
    88.                         throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");   
    89.                 }   
    90.                 sb.append(strNum);   
    91.                 return sb.toString();   
    92.         }   
    93.   
    94.         /**  
    95.          * 根据数字生成一个定长的字符串,长度不够前面补0  
    96.          *  
    97.          * @param num             数字  
    98.          * @param fixdlenth 字符串长度  
    99.          * @return 定长的字符串  
    100.          */   
    101.         public static String toFixdLengthString(int num, int fixdlenth) {   
    102.                 StringBuffer sb = new StringBuffer();   
    103.                 String strNum = String.valueOf(num);   
    104.                 if (fixdlenth - strNum.length() >= 0) {   
    105.                         sb.append(generateZeroString(fixdlenth - strNum.length()));   
    106.                 } else {   
    107.                         throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");   
    108.                 }   
    109.                 sb.append(strNum);   
    110.                 return sb.toString();   
    111.         }   
    112.   
    113.         public static void main(String[] args) {   
    114.                 System.out.println(generateString(15));   
    115.                 System.out.println(generateMixString(15));   
    116.                 System.out.println(generateLowerString(15));   
    117.                 System.out.println(generateUpperString(15));   
    118.                 System.out.println(generateZeroString(15));   
    119.                 System.out.println(toFixdLengthString(123, 15));   
    120.                 System.out.println(toFixdLengthString(123L, 15));   
    121.         }   
    122. }  
    [java] view plain copy
     
    1. import java.util.Random;   
    2.   
    3. /**  
    4. * 随机数、随即字符串工具  
    5. */   
    6. public class RandomUtils {   
    7.         public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";   
    8.         public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";   
    9.         public static final String numberChar = "0123456789";   
    10.   
    11.         /**  
    12.          * 返回一个定长的随机字符串(只包含大小写字母、数字)  
    13.          *  
    14.          * @param length 随机字符串长度  
    15.          * @return 随机字符串  
    16.          */   
    17.         public static String generateString(int length) {   
    18.                 StringBuffer sb = new StringBuffer();   
    19.                 Random random = new Random();   
    20.                 for (int i = 0; i < length; i++) {   
    21.                         sb.append(allChar.charAt(random.nextInt(allChar.length())));   
    22.                 }   
    23.                 return sb.toString();   
    24.         }   
    25.   
    26.         /**  
    27.          * 返回一个定长的随机纯字母字符串(只包含大小写字母)  
    28.          *  
    29.          * @param length 随机字符串长度  
    30.          * @return 随机字符串  
    31.          */   
    32.         public static String generateMixString(int length) {   
    33.                 StringBuffer sb = new StringBuffer();   
    34.                 Random random = new Random();   
    35.                 for (int i = 0; i < length; i++) {   
    36.                         sb.append(allChar.charAt(random.nextInt(letterChar.length())));   
    37.                 }   
    38.                 return sb.toString();   
    39.         }   
    40.   
    41.         /**  
    42.          * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)  
    43.          *  
    44.          * @param length 随机字符串长度  
    45.          * @return 随机字符串  
    46.          */   
    47.         public static String generateLowerString(int length) {   
    48.                 return generateMixString(length).toLowerCase();   
    49.         }   
    50.   
    51.         /**  
    52.          * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)  
    53.          *  
    54.          * @param length 随机字符串长度  
    55.          * @return 随机字符串  
    56.          */   
    57.         public static String generateUpperString(int length) {   
    58.                 return generateMixString(length).toUpperCase();   
    59.         }   
    60.   
    61.         /**  
    62.          * 生成一个定长的纯0字符串  
    63.          *  
    64.          * @param length 字符串长度  
    65.          * @return 纯0字符串  
    66.          */   
    67.         public static String generateZeroString(int length) {   
    68.                 StringBuffer sb = new StringBuffer();   
    69.                 for (int i = 0; i < length; i++) {   
    70.                         sb.append('0');   
    71.                 }   
    72.                 return sb.toString();   
    73.         }   
    74.   
    75.         /**  
    76.          * 根据数字生成一个定长的字符串,长度不够前面补0  
    77.          *  
    78.          * @param num             数字  
    79.          * @param fixdlenth 字符串长度  
    80.          * @return 定长的字符串  
    81.          */   
    82.         public static String toFixdLengthString(long num, int fixdlenth) {   
    83.                 StringBuffer sb = new StringBuffer();   
    84.                 String strNum = String.valueOf(num);   
    85.                 if (fixdlenth - strNum.length() >= 0) {   
    86.                         sb.append(generateZeroString(fixdlenth - strNum.length()));   
    87.                 } else {   
    88.                         throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");   
    89.                 }   
    90.                 sb.append(strNum);   
    91.                 return sb.toString();   
    92.         }   
    93.   
    94.         /**  
    95.          * 根据数字生成一个定长的字符串,长度不够前面补0  
    96.          *  
    97.          * @param num             数字  
    98.          * @param fixdlenth 字符串长度  
    99.          * @return 定长的字符串  
    100.          */   
    101.         public static String toFixdLengthString(int num, int fixdlenth) {   
    102.                 StringBuffer sb = new StringBuffer();   
    103.                 String strNum = String.valueOf(num);   
    104.                 if (fixdlenth - strNum.length() >= 0) {   
    105.                         sb.append(generateZeroString(fixdlenth - strNum.length()));   
    106.                 } else {   
    107.                         throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");   
    108.                 }   
    109.                 sb.append(strNum);   
    110.                 return sb.toString();   
    111.         }   
    112.   
    113.         public static void main(String[] args) {   
    114.                 System.out.println(generateString(15));   
    115.                 System.out.println(generateMixString(15));   
    116.                 System.out.println(generateLowerString(15));   
    117.                 System.out.println(generateUpperString(15));   
    118.                 System.out.println(generateZeroString(15));   
    119.                 System.out.println(toFixdLengthString(123, 15));   
    120.                 System.out.println(toFixdLengthString(123L, 15));   
    121.         }   
    122. }  


    运行结果:

    [html] view plain copy
     
      1. vWMBPiNbzfGCpHG   
      2. 23hyraHdJkKPwMv   
      3. tigowetbwkm1nde   
      4. BPZ1KNEJPHB115N   
      5. 000000000000000   
      6. 000000000000123   
      7. 000000000000123   
      8.   
      9. Process finished with exit code 0  
  • 相关阅读:
    mongodb的学习-1-NoSQL
    mongodb的学习-3-在Mac上的安装配置
    面试题之算法与编程
    笔试题之javaweb
    笔试题之j2ee
    笔试题之代码查错
    笔试题之java基础
    javaweb笔记分享
    过滤器入门
    jsp入门
  • 原文地址:https://www.cnblogs.com/sharpest/p/7879257.html
Copyright © 2011-2022 走看看