i have written this method
public boolean passwordCheck(String password)
{
boolean isValid = false;
int numCount = 0;
if(password.length() < 8){
return false;
}
for(int i = 0; i < password.length(); i++){
if(!Character.isLetterOrDigit(password.charAt(i)))
{
return false;
}
else{
return true;
}
}
return isValid;
}
and when I do passwordCheck("a * b * e * d * c") (imagine no spaces in between the asterisks) it should return false because i have the
if(!Character.isLetterOrDigit(password.charAt(i)))
so since there are things in the password that are not valid characters i would expect it would return false but that is not the case.
您的第一个字符是字母或数字后,您将返回true。
You don't want to return true
until after you've checked every character. But currently, you're returning true
as soon as you've checked the first one.
One possible solution is to get rid of the else
clause, and move the return true;
down outside the loop, like this.
for(int i = 0; i < password.length(); i++){
if(!Character.isLetterOrDigit(password.charAt(i)))
{
return false;
}
}
return true;
If you use "return" when a character is "unacceptable" ( return false
) This is OK - because "one bad apple will spoil the bunch".
And also: "One invalid character means the whole password is invalid..." But if you return true
just because one character is valid / true. That is the mistake in your method. –
public boolean passwordCheck(String password)
{
if(password.length() < 8) return false;
for(int i=0; i < password.length(); i++)
if(!Character.isLetterOrDigit(password.charAt(i)))
return false;
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.