自备小题目(一)随机字符串

package com.pro.test;

import java.util.Random;

public class Test2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String st = yzrd(20);
        System.out.println(st);
    }
    
    private static String yzrd(int i){
        while(true){
            String st = makeRandomPassword(i);
            if (st.matches(".*[a-z]{1,}.*")
                    && st.matches(".*[A-Z]{1,}.*")
                    && st.matches(".*\\d{1,}.*")
                    && st.matches(".*[~!@#$%^&*\\.?]{1,}.*")) {
                return st;
            }
        }
    }

    private static String makeRandomPassword(int i) {
        // TODO Auto-generated method stub
        char c[]="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*.?".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for(int j = 0 ;j < i ;j++){
            sb.append(c[r.nextInt(c.length)]);
        }
        return sb.toString();
    }

}

 

posted @ 2018-09-21 11:23  不会飞的云930  阅读(156)  评论(0编辑  收藏  举报