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; }}