gpt4 book ai didi

java - boolean 帮助 : Testing the parameters for a password JAVA

转载 作者:行者123 更新时间:2023-12-02 04:19:30 27 4
gpt4 key购买 nike

任务:

该程序应检查输入的密码长度是否至少为 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");
}

如果我输入密码“water”,我会得到:

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

最佳答案

我认为大小写检查应该反之亦然:

hasUppercase = !password.equals(password.toLowerCase());
hasLowercase = !password.equals(password.toUpperCase());

因为密码的小写版本等于密码,前提是它不包含大写字母。

另外两项检查可以这样完成:

hasDigit = password.matches(".*[0-9].*");
hasSpecial = !password.matches("[A-Za-z0-9]*");

关于java - boolean 帮助 : Testing the parameters for a password JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939637/

27 4 0