您的当前位置:首页正文

生成指定个数的随机码,同时包含大小写字母和数字

2024-11-08 来源:个人技术集锦

【华三通讯2018年校招编程题】题目:编写一个函数,用于生成随机密码,参数为随机密码长度,密码必须同时包含大小写字母和数字

/**
 * Created by lxw, liwei4939@126.com on 2017/9/23.
 */
import java.util.*;
public class randomPW {
    public static String randomPW(int len){
        if(len<3)
            throw new IllegalArgumentException("长度不能小于3");
        int lowCaseNO=0, highCaseNO, numberNO;
        Random random = new Random();
        while (true){
            lowCaseNO = random.nextInt(len)+1;
            if(lowCaseNO<=len-2)
                break;
        }
        while (true){
            highCaseNO = random.nextInt(len-lowCaseNO)+1;
            if(highCaseNO<=len-lowCaseNO-1)
                break;
        }
        numberNO = len-lowCaseNO-highCaseNO;
        int select =-1;
        int count = 0;
        StringBuilder sb = new StringBuilder();
        while(count<len){
            select = random.nextInt(3)+1;
            switch (select){
                case 1:
                    if(highCaseNO==0)
                        continue;
                    char ch = (char)(random.nextInt(26)+'A');
                    sb.append(ch);
                    highCaseNO--;
                    count++;
                    break;
                case 2:
                    if(lowCaseNO==0)
                        continue;
                    char lowch = (char)(random.nextInt(26)+'a');
                    sb.append(lowch);
                    lowCaseNO--;
                    count++;
                    break;
                case 3:
                    if(numberNO==0)
                        continue;
                    char numch = (char)(random.nextInt(9)+'0');
                    sb.append(numch);
                    numberNO--;
                    count++;
                    break;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args){
       Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int len = sc.nextInt();
            String str = randomPW(len);
            System.out.println(str);
        }
    }
}
参考链接:http://m./brillianteagle/article/details/50513715?from=groupmessage

Top