`
nuistcc
  • 浏览: 82280 次
社区版块
存档分类
最新评论

Java生成字母和数字组成的随机字符串

阅读更多

    在业务开发过程中经常遇到生成随机字符串,用于密钥、密码、口令或其他标识使用。

    下面就介绍一下通过Java程序生成这些随机字符串的方法。

     1. 随机生成n位由字母或数字组成的字符串

 public static String getRandomCharacterAndNumber(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
                // int choice = 97; // 指定字符串为小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

 

2. 结果校验

public static boolean isRandomUsable(String str) {
        String regExp = "^[0-9a-zA-Z]{6}$";
        Pattern pat = Pattern.compile(regExp);
        Matcher mat = pat.matcher(str);
        return mat.matches();
    }

 

3. 测试代码

public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            String str = getRandomCharacterAndNumber(6);
            System.out.println(str);
            System.out.println(isRandomUsable(str));
        }
    }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics