gpt4 book ai didi

Java 密码检查

转载 作者:行者123 更新时间:2023-11-30 07:30:48 25 4
gpt4 key购买 nike

我遇到的问题是让它在确认密码之前重复第一个密码过程。

The password must be at least 8 characters long.

The password must contain at least:

  • one alpha character [a-zA-Z]
  • one numeric character [0-9]
  • one character that is not alpha or numeric, such as ! # @ $ % ^ & * ( ) - _ = + [ ] ; : ' " , < . > / ?

The password must not:

  • contain spaces
  • begin with an exclamation [!] or a question mark [?]

这是代码

public static void main(String[] args) {

//declare variables
String inputPassword; // variable for password
String confirmPassword;

// set up input stream from the keyboard
Scanner input = new Scanner (System.in);

// ask for password
System.out.print("Password : ");
inputPassword = input.next();
passCheck(inputPassword);

System.out.print("Please confirm your password : ");
confirmPassword = input.next();


if(inputPassword.matches(confirmPassword)){
System.out.println("Password successfully created.");
} else {
System.out.println("Passwords do not match.");
}


}

public static void passCheck(String password){
boolean valid = true;
if(password.length() < 8){
System.out.println("Password is not eight characters long.");
valid = false;
}
String upperCase = "(.*[A-Z].*)";
if(!password.matches(upperCase)){
System.out.println("Password must contain at least one capital letter.");
valid = false;
}
String numbers = "(.*[0-9].*)";
if(!password.matches(numbers)){
System.out.println("Password must contain at least one number.");
valid = false;
}
String specialChars = "(.*[ ! # @ $ % ^ & * ( ) - _ = + [ ] ; : ' \" , < . > / ?].*)";
if(!password.matches(specialChars)){
System.out.println("Password must contain at least one special character.");
valid = false;
}
String space = "(.*[ ].*)";
if(password.matches(space)){
System.out.println("Password cannot contain a space.");
valid = false;
}
if(password.startsWith("?")){
System.out.println("Password cannot start with '?'.");
valid = false;

}
if(password.startsWith("!")){
System.out.println("Password cannot start with '!'.");
valid = false;
}
if(valid){
System.out.println("Password is valid.");
}
}

我得到的是在它告诉我其中一个问题后,它会要求确认密码,这不是我想要的。

最佳答案

如果密码无效,用户无需重复密码

我对此的看法;

  System.out.print("Password : ");
inputPassword = input.next();


if(passCheck(inputPassword))
{
System.out.print("Please confirm your password : ");
confirmPassword = input.next();


if(inputPassword.matches(confirmPassword)){
System.out.println("Password successfully created.");
} else {
System.out.println("Passwords do not match.");
}
}
else {....}

......

编辑:我注意到你的方法 passCheck 的返回类型是 void。尝试将其更改为 boolean 值

关于Java 密码检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com