我使用以下脚本检查密码的长度、大写字母数和数字数。
有没有办法让它也检查小写字母的数量?我试过几次修改我的代码,但每次都会破坏另外两次检查。提前感谢!
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
boolean success=false;
while(!success){
System.out.print("Password: ");
inputPassword = input.next();
System.out.println(PassCheck(inputPassword));
if(PassCheck(inputPassword).equals("Valid Password")) success = true;
System.out.println("");
}
}
public static String PassCheck(String Password) {
String result = "Valid Password";
int length = 0;
int numCount = 0;
int capCount = 0;
for (int x = 0; x < Password.length(); x++) {
if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58) || (Password.charAt(x) >= 64 && Password.charAt(x) <= 91) ||
(Password.charAt(x) >= 97 && Password.charAt(x) <= 122)) {
} else {
result = "Password Contains Invalid Character!";
}
if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {
numCount++;
}
if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {
capCount++;
}
length = (x + 1);
}
if (numCount < 2) {
result = "digits";
}
if (capCount < 2) {
result = "uppercase letters";
}
if (capCount < 2) {
result = "uppercase letters";
}
if (numCount < 2 && capCount < 2)
{
result = "uppercase letters digits";
}
if (length < 2) {
result = "Password is Too Short!";
}
return (result);
}
}
逐个检查每个字符是一项乏味的任务,会增加逻辑错误。可以使用正则表达式进行此操作。您修改的"PassCheck"方法:-
public static String PassCheck(String Password) {
int length = Password.length();
if(length<2)
return "Password is Too Short!";
String regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$";
boolean d = Password.replaceAll("[^0-9]", "").length()<2;
boolean u = Password.replaceAll("[^A-Z]", "").length()<2;
boolean l = Password.replaceAll("[^a-z]", "").length()<2;
if(d && u)
return "digits uppercase";
else if(l&&u)
return "lowercase uppercase";
else if(l&&d)
return "lowercase digits";
else if(d)
return "digits";
else if(u)
return "uppercase";
else if(l)
return "lowercase";
else if(!(Password.matches(regex)))
return "Password contains Invalid Character!";
return "Valid Password";
}