随机数生成

时间 2018/12/23 10:24:00 加载中...

生成随机数

我们常用的是生成一个唯一的随机数,那就是使用GUID。
我们还可能用到生成指定字符串长度的随机数,
比如说4位图像验证码或6位手机验证码。

生成方法如下:

  1. import java.text.SimpleDateFormat;
  2. import java.util.Date;
  3. import java.util.Random;
  4. import org.apache.commons.codec.digest.DigestUtils;
  5. public class RandomCode {
  6. public static void main(String[] args){
  7. String code = getCode(4);
  8. P.print(code);
  9. /*其他随机字符串生成方法*/
  10. P.print(java.util.UUID.randomUUID().toString());
  11. P.print(java.util.UUID.randomUUID().toString().replace("-",""));
  12. code = getCode(4);
  13. String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
  14. String md5 = DigestUtils.md5Hex(code + time + "540de77bc32847828b85c84217ca4c32");
  15. P.print("thecode:");
  16. P.print(md5);
  17. }
  18. /**
  19. * @param codeLength 随机验证码的长度
  20. * @return 由大小写字母和数字组成的字符串
  21. */
  22. public static String getCode(int codeLength) {
  23. Random randomer = new Random();
  24. StringBuilder builder = new StringBuilder();
  25. char[] elements = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  26. 'S', 'T', 'V', 'U', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  27. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8',
  28. '9' };
  29. for (int i = 0; i < codeLength; i++) {
  30. int index = randomer.nextInt(elements.length);
  31. builder.append(elements[index]);
  32. }
  33. return builder.toString();
  34. }
  35. }
扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/random-num.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。