日期:2014-05-20  浏览次数:20965 次

有关String的问题
要求写一个类函数去判断一个字符串是不是可用的密码。密码规则如下:
1,密码必须有至少8个字符组成。
2,密码只由字母和数字组成。
3,密码必须包含至少两个数字。
4,密码必须有至少一个大写字母。
这个程序要让用户输入一个密码,如果密码可用要显示“密码可用”,如果密码不符合要求显示“密码不可用”。

希望大神们能够帮助写出来,我朋友的作业。谢谢各位了!!!

------解决方案--------------------
Java code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidate {

    static boolean validate(String pwd) {

        int lCount = 0;
        int uCount = 0;
        int nCount = 0;
        if (pwd != null && pwd.length() >= 8) {
            Matcher match = Pattern.compile("[a-z]").matcher(pwd);
            while (match.find())
                lCount++;
            match = Pattern.compile("[A-Z]").matcher(pwd);
            while (match.find())
                uCount++;
            match = Pattern.compile("\\d").matcher(pwd);
            while (match.find())
                nCount++;
            if (uCount > 0 && nCount > 2 && (lCount+uCount+nCount)==pwd.length())
                return true;
        }
        return false;
    }

    static String validatePassword() {
        String pwd = "";
        InputStreamReader stdin = new InputStreamReader(System.in);// 键盘输入
        BufferedReader bufin = new BufferedReader(stdin);
        try {
            System.out.print("请输入密码,输入quit退出程序");
            while(true) {
                pwd = bufin.readLine();
                if("quit".equals(pwd)) {
                    System.out.println("程序退出......");
                    System.exit(0);
                }
                if(validate(pwd)) {
                    System.out.println("密码可用");
                } else {
                    System.out.println("密码不可用");
                }
            }
        } catch (IOException E) {
            System.out.println("发生I/O错误!!! ");
        }
        return pwd;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        validatePassword();
    }
}