我用Java写的PasswordGenerate改进版源码

Java logo
前段时间用Java编写过一个名叫PasswordGenerate的密码生成器,最近看到别人写的一段PHP代码,从中受到启发,于是对我的这个密码生成器进行了改进,优化了不少代码行,详细请见下面的源代码:

package passwordgenerate;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;
 
/**
 * 密码生成器
 * @author Jason jasonwei06@hotmail.com
 * @version 2.0
 */
public class Main {
    int intPassLength = 0; //密码长度
    char arrayString[] = new char[62]; //候选字符数组
 
    /**
     * 生成密码
     * @param intPassLength 密码长度
     * @return
     */
    public String doGenerate(final int intPassLength) {
        int intTemp;
        String strPassword = "";
        Random rand = new Random();
        for(int i = 0; i < intPassLength; i++) {
            intTemp = rand.nextInt(63);
            strPassword += this.arrayString[intTemp];
        }
        return strPassword;
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        final Main Main = new Main();
        //确定密码长度
        while(true) {
            System.out.print("请输入密码长度[8-64]:");
            final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String inputThreadAmount = null;
            try {
                inputThreadAmount = br.readLine();
                if(inputThreadAmount.matches("^[0-9]+$")) {
                    Main.intPassLength = Integer.parseInt(inputThreadAmount);
                    if(Main.intPassLength >= 8 && Main.intPassLength <= 64) {
                        break;
                    } else {
                        System.out.println("长度超出范围,请输入8至64之间的数字!");
                    }
                } else {
                    System.out.println("输入格式有误!请输入8至64之间的数字!");
                }
            } catch (final Exception e) {
                e.getMessage();
            }
        }
 
        int j = 0;
        for(int i = 48; i <= 57; i++) { //0-9
            Main.arrayString[j] = (char)i;
            j++;
        }
        for(int i = 65; i <= 90; i++) { //A-Z
            Main.arrayString[j] = (char)i;
            j++;
        }
        for(int i = 97; i <= 122; i++) { //a-z
            Main.arrayString[j] = (char)i;
            j++;
        }
 
        String strPassword = Main.doGenerate(Main.intPassLength);
        System.out.print("本次生成的密码为:" + strPassword);
    }
}

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

相关内容:

发表评论