码迷,mamicode.com
首页 > 编程语言 > 详细

java生成随机数

时间:2015-02-25 10:12:12      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

生成不定长度的随机字符串:

public class RandomUtils {
    public static final String allChar="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static String generateString(){
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        int x = random.nextInt(47);
        for (int i = 0; i < x; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }
    
    //test code
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(generateString());
        }
        
    }
}

生成指定长度的字符串:

    public static final String randomString(int length) {
          Random randGen = null;
          char[] numbersAndLetters = null;
            if (length < 1) {
                return null;
            }
            if (randGen == null) {
                   randGen = new Random();
                   numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
                      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                    }
            char [] randBuffer = new char[length];
            for (int i=0; i<randBuffer.length; i++) {
                randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
            }
            return new String(randBuffer);
    }

 

java生成随机数

标签:

原文地址:http://www.cnblogs.com/hutton/p/4299146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!