我几周前刚开始使用java,正在尝试制作一个程序来验证密码是否至少有10个字符,至少有以下各一个:大写、小写、数字,并且只是字母数字字符。
下面是我到目前为止的代码。实际上,它比代码更英语,但我想做的是在一个 boolean 值下运行几个循环(至少我认为我正在做的事情)。您能否帮助我了解 boolean 值到底是如何工作的,以及是否可以在一个 boolean 值下测试多个条件,就像我在下面尝试做的那样?
谢谢!
public class validatingPassword
{
public static void main(String[] args)
{
String password= isSecurePassword("testcase");
System.out.println(isSecurePassword);
}
public static boolean isSecurePassword(String password)
{
password.charAt(x);
int lengthPassword= password.length();
if (lengthPassword < 10);
return false;
for (int x = 0; x < lengthPassword; x++)
{
if ('A' <=x && x <= 'Z');}
else if
return false;
for (int x = 0; x< lengthPassword; x++)
{
('a' <=x && x <= 'z'); }
else if
return false:
for (int x = 0; x < lengthPassword; x++)
{
('0' <=x && x <= '9');}
return true;
}
else if
{
x++;
return false;
}
}
}
最佳答案
我只是给出了未记录的正确代码。因为我认为您的想法是正确的,但缺少一些 Java 语法。您可以通过所有命令单步调试代码。
public class ValidatingPassword {
public static void main(String[] args) {
String[] passwords = { "testcase", "T3stCas3%45" };
for (String password : passwords) {
System.out.println(password + " : " + isSecurePassword(password));
}
}
/**
* Is this a secure password?
* At least 10 characters, at least one capital letter, one small
* letter and one digit.
*
* @param password never null.
* @return whether password is secure.
*/
public static boolean isSecurePassword(String password) {
int lengthPassword = password.length();
if (lengthPassword < 10) {
return false;
}
boolean hasCapital = false;
boolean hasSmallLetter = false;
boolean hasDigit = false;
for (int i = 0; i < lengthPassword; i++) {
char ch = password.charAt(i);
if ('A' <= ch && ch <= 'Z') {
hasCapital = true;
}
if ('a' <= ch && ch <= 'z') {
hasSmallLetter = true;
}
if ('0' <= ch && ch <= '9') {
hasDigit = true;
}
}
return hasCapital && hasSmallLetter && hasDigit;
}
}
关于java - 密码 validator java : linking booleans?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9355104/