我正在尝试创建一个程序,要求用户输入一个条件至少包含10个字母且至少包含2个数字的密码。 到目前为止,这是我提出的,但程序会将任意数量的字母或数字作为有效密码。
package password;
import java.util.Scanner;
public class Password {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String password;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a password with 10 characters total with "+
"2 numbers: ");
password=keyboard.nextLine();
System.exit(0);
}
public static boolean passwordCheck(String password)
{
if (password.length() <10) return false ;
int letterCount = 0;
int numCount =0;
for (int i =0; i < password.length (); i++ )
{char ch = password.charAt(i);
if (letter(ch)) letterCount++;
else if (numeric(ch)) numCount++;
else return false;
}
return (letterCount >= 2 && numCount >= 2);
}
public static boolean letter(char ch)
{
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ;
}
public static boolean numeric(char ch)
{
return(ch >= '0' && ch <= '9');
}
}
答案 0 :(得分:1)
试试这个。
if (password.length() < 10) {
return false;
} else {
char c;
int count = 1;
for (int i = 1; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
if (count < 2) {
return false;
}
}
}
}
return true;
}