【发布时间】:2019-02-21 21:42:35
【问题描述】:
这是一个课堂作业,我必须检查用户输入的密码。我似乎无法弄清楚如何检查有效字符的密码。这些是要求:
1.循环直到输入有效密码。
一个有效的密码:
至少应包含 1 个大写字母。
至少应包含 1 个小写字母。
至少应包含 6 个字符。
应该至少有 1 个数字。
只能包含字母、数字或下划线
我需要一些关于将 hasValidCharacters 设置为 true 并将 isValid 设置为 true 的 if 语句的帮助,以便我可以显示正确的密码。
String password;
boolean isValid = false;
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
boolean hasValidCharacters = false;
boolean hasLength = false;
//Loop until a valid password is entered
System.out.print("Enter password: ");
password = kb.nextLine();
char ch;
for(int i=0;i<password.length();i++)
{
ch = password.charAt(i);
//Display all appropriate error messages
if(Character.isUpperCase(ch))
hasUpperCase=true;
else
System.out.println("ERROR: should have at least 1 uppercase letter.");
if(Character.isLowerCase(ch))
hasLowerCase=true;
else
System.out.println("ERROR: should have at least 1 lowercase letter.");
if(password.length()>6)
hasLength=true;
else
System.out.println("ERROR: should be at least 6 characters long.");
if(Character.isDigit(ch))
hasDigit=true;
else
System.out.println("ERROR: should have at least 1 digit.");
if()
hasValidCharacters=true;
else
System.out.println("ERROR: should only contain letters, digits or underscore");
//Display password when valid
if(isValid=true)
System.out.println(password + " is valid. ");
else
System.out.print("Enter valid password: ");
password = kb.nextLine();
}
}
}
【问题讨论】: