博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java生成六位验证码
阅读量:4563 次
发布时间:2019-06-08

本文共 960 字,大约阅读时间需要 3 分钟。

import java.util.Random;public class random {    public static String getrandom(){    String code = "";    Random random = new Random();    for (int i = 0; i < 6; i++) {        int r = random.nextInt(10); //每次随机出一个数字(0-9)        code = code + r;  //把每次随机出的数字拼在一起    }    return code;        }}

以上代码是复制网上的,也运用到了自己的练习项目中。以前老师讲过一种用Math.random()实现。

random.nextInt()与Math.random()的区别是:

                               Math.random()是方法,random.nextInt()是一个类。Math.random()是Random.nextDouble()的一个内部方法. 

 

java中生成的随机数都是伪随机,也就是根据特定算法算出来的,只要理解了算法,下一个随机数是可以算出来的。不过在我们平时使用中够用了

                            

在百度中看到random.nextInt()的效率比Math.random()高50%-80%。所以就用了上面代码的方法。

附上Math.random()生成六位验证码的方法

public class Random {    public static Integer getRandom(){        String randomString=null;        Integer random = null;        do{            random=(int)(Math.random()*1000000);            randomString=random+"";        }        while(randomString.length()<6);        return random;    }}

 

转载于:https://www.cnblogs.com/txbblog/p/10226441.html

你可能感兴趣的文章
面向对象之多态性
查看>>
树状数组
查看>>
【2019.8.14 慈溪模拟赛 T1】我不是!我没有!别瞎说啊!(notme)(BFS+DP)
查看>>
多任务--进程 及 进程间通信
查看>>
多线程/多进程+QProgressBar实现进度条
查看>>
多任务(进程)案例----- 拷贝文件夹
查看>>
Kotlin的快速入门
查看>>
底层原理
查看>>
21. Merge Two Sorted Lists
查看>>
shiro设置加密算法源码解析
查看>>
第二次冲刺
查看>>
实验四
查看>>
win8.1镜像制作
查看>>
Windows 服务开发框架介绍 - Topshelf
查看>>
php,字符串(二)
查看>>
Sizzle前奏
查看>>
Paint Chain HDU - 3980(sg)
查看>>
Chales常用操作
查看>>
C++ 运算符重载<<
查看>>
windows镜像
查看>>