我已经写了一些代码,但我似乎无法弄清楚如何获得字符,数字或符号的确切数量。我修复了我的代码,但它不起作用,我不确定为什么。
我的要求是
编写一个 Java 程序,提示用户输入与特定模式匹配的密码。您的程序必须批准用户的条目。以下是模式,按此顺序排列:
-1 or more upper case letters
-two lower case letters
-1 or 2 digits
-zero or 1 upper case letters
-any two of this group @#$%^&
我的代码:
import java.util.Scanner;
public class TestingCenter {
public static void main(String[] args) {
int digit=0;
int special=0;
int upCount=0;
int upCount2=0;
int loCount=0;
String password;
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
password = scan.nextLine();
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isUpperCase(c)){
upCount++;
}
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isDigit(c)){
digit++;
}
if(Character.isUpperCase(c)){
upCount2++;
}
if(c>=33&&c<=46||c==64){
special++;
}
}
if(special==2&&loCount==2&&upCount>=1&&(digit==1||digit==2)&&upCount2<=1){
System.out.println(" Password is good:");
}
}
}
如果我理解正确,按此顺序字面意思是按给定顺序排列。
如果是这种情况,您需要正则表达式。忘记数字符。
[A-Z]+
1 个或多个大写字母- 两个小写字母
[a-z]{2}
- 1 或 2 位数字
d{1,2}
- 零个或 1 个大写字母
[A-Z]?
- 此组中的任意两个 @#$%^&
[@#$%^&]{2}
所以
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
String password = scan.nextLine();
System.out.println(password.matches("[A-Z]+[a-z]{2}\d{1,2}[A-Z]?[@#$%^&]{2}");
如果这不是您的说明的意思,请查看您的条件。显然,并非所有内容都应该>= 1