如何检查字符串有一个大写.lowercase或数字?

时间:2014-10-21 05:48:05

标签: java

在这里,我使用此代码生成一个密码,该密码应包含大写,小写和数字以及特殊字符。这是我的检查代码。

String randomPassword = genRanPass();
        boolean hasUppercase = !randomPassword.equals(randomPassword.toLowerCase());
        boolean hasLowercase = !randomPassword.equals(randomPassword.toUpperCase());
        boolean hasNumber  = randomPassword.matches(".*\\d.*");
        if(!(randomPassword.contains("!") || randomPassword.contains("@") || randomPassword.contains("#") || randomPassword.contains("$") || randomPassword.contains("_") || randomPassword.contains("-"))){
             while(!hasUppercase && hasLowercase && hasNumber) 
             {
             randomPassword = genRanPass();
             }

          }else{

             while(!hasUppercase && hasLowercase && hasNumber) 
                 {
                 randomPassword = genRanPass();
                 }

                return randomPassword;

        }

genRanPass(); generating a password having random number,a spcial char,a letter Uppercase and lower case

but i got hnga$VVj from my method  and when i am checking 

while(!hasUppercase && hasLowercase && hasNumber) 
                 {
                 randomPassword = genRanPass();
                 }

                return randomPassword;
   while(!hasUppercase && hasLowercase && hasNumber) its became true,true and false,its not going inside this method plase help me.
                 {       

1 个答案:

答案 0 :(得分:1)

我强烈建议您使用直接for-each loopCharacter中的实用程序方法。像,

public static boolean isPasswordValid(String password) {
    if (password == null) return false;
    boolean hasUpper = false;
    boolean hasLower = false;
    boolean hasNumber = false;
    boolean hasSpecial = false;
    for (char ch : password.toCharArray()) {
        if (Character.isUpperCase(ch)) {
            hasUpper = true;
        } else if (Character.isLowerCase(ch)) {
            hasLower = true;
        } else if (Character.isDigit(ch)) {
            hasNumber = true;
        } else {
            hasSpecial = true;
        }
    }
    return hasUpper && hasLower && hasNumber && hasSpecial;
}