【发布时间】:2015-10-05 00:01:31
【问题描述】:
任务:
此程序应检查输入的密码是否至少包含 8 个字符、一个大小写字母、一个数字和一个特殊字符。
代码:
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!@#$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t " + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toUpperCase());
hasLowercase = !password.equals(password.toLowerCase());
hasDigit = !password.matches("[0-9]");//checks for digits
hasSpecial = !password.matches("[A-Za-z]*"); //for anything not a letter in the ABC's
// the following checks if any of the instances are false, of so prints the statement
if(hasLength)
{
System.out.println("Verdict: Invalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("Verdict: Invalid, Must have an uppercase Character");
}
if(!hasLowercase)
{
System.out.println("Verdict: Invalid, Must have a lowercase Character");
}
if(!hasDigit)
{
System.out.println("Verdict: Invalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("Verdict: Invalid, Must have a special character");
}
如果我输入密码“水”,我得到:
Entered Password: water
Verdict: Invalid, Must have at least 8 characters
Verdict: Invalid, Must have a lowercase Character
Verdict: Invalid, Must have a special character
【问题讨论】:
-
!password.equals(password.toLowerCase());不会测试“单个”小写字符,但如果整个密码都是小写,那么您的大写检查也是如此 -
我正要和我上面那个人说同样的话!
-
哇哦,呵呵。检查小写字符的好方法是什么。在 If 循环中检查每个字母是大写还是小写?
-
您可以改用
hasUppercase = password.matches("(?s).*[A-Z]*");和hasLowercase = password.matches("(?s).*[a-z]*"); -
或
import static org.apache.commons.lang3.StringUtils.*; /* ... */ boolean ok = !isAllUpperCase(password) && !isAllLowerCase(password);