某些网站对密码规定了某些规则。我正在编写一个方法来检查字符串是否是有效的密码。
密码的规则是:
我想出了大部分代码,我认为我现在有一些概念正确无论我输入什么密码打印出“无效密码”..我试过运行调试器但是真的很困惑。
这是我的代码:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
System.out.print("Enter a password");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
boolean isCorrect = checkPassword(password);
if(isCorrect)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
//this method checks the password
public static boolean checkPassword(String password)
{
int countDigit = 0;
if (password.length() >=8 ){
return false;
}
for(int i = 0; i <password.length(); i++)
{
if(!(Character.isLetterOrDigit(password.charAt(i))))
{
return false;
}
}
for(int i = 0; i<password.length(); i++){
if((Character.isDigit(password.charAt(i)))){
countDigit = countDigit + 1;
}
}
if (countDigit >= 2){
return true;
}
else
return false;
}
}
答案 0 :(得分:0)
错误在于:
if (password.length() >=8 ){
return false;
}
这里你说如果密码长度大于或等于8个字符,则密码无效,这与要求完全相反。将其更改为:
if (password.length() < 8 ){
return false;
}
此外,您可以减少for循环的数量,以使代码更快。您可以计算位数,并在相同的for循环中检查isLetterOrDigit
:
int countDigit = 0;
if (password.length() < 8) {
return false;
}
for (int i = 0; i < password.length(); i++) {
if (!(Character.isLetterOrDigit(password.charAt(i)))) {
return false;
}
if ((Character.isDigit(password.charAt(i)))) {
countDigit = countDigit + 1;
}
}
if (countDigit >= 2) {
return true;
} else {
return false;
}