我写了一个方法,让用户输入密码并且要符合以下规格:
1. 至少8个字符长
2. 包含大写字母
3. 包含小写字母
4. 包含特殊字符
但是当我输入时,输出结果没有考虑特殊字符,会出现错误。
这是我的代码:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a given password : ");
String passwordhere = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
String confirmhere = in.nextLine();
System.out.println("your password is: " + passwordhere);
while (!passwordhere.equals(confirmhere) || !isValid(passwordhere)) {
System.out.println("The password entered here is invalid");
System.out.print("Please enter the password again.it must be valid : ");
String Passwordhere = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
}
}
public static boolean isValid(String passwordhere) {
if (passwordhere.length() < 8) {
return false;
} else {
for (int p = 0; p < passwordhere.length(); p++) {
if (Character.isUpperCase(passwordhere.charAt(p))) {
}
}
for (int q = 0; q < passwordhere.length(); q++) {
if (Character.isLowerCase(passwordhere.charAt(q))) {
}
}
for (int r = 0; r < passwordhere.length(); r++) {
if (Character.isDigit(passwordhere.charAt(r))) {
}
}
for (int s = 0; s < passwordhere.length(); s++) {
if (Character.isSpecialCharacter(passwordhere.charAt(s))) {
}
}
return true;
}
}
此外,另一个问题是,例如,假设用户将
bob123
作为其密码输入。我该如何让循环告诉用户它需要什么才能成为正确的密码?
在上面的示例中,缺少一个大写字母和一个符号(*&amp; ^..等)。
我该如何添加此内容以每次用户创建密码时打印出来,并直到他们获得通过代码的所有规格的正确密码?
Character.isSpecialCharacter
。 - OneCricketeer