提示用户输入与特定模式匹配的密码

时间:2017-06-18 04:54:30

标签: java

我已经编写了一些代码,但我似乎无法弄清楚如何获得字符,数字或符号的确切数量。我修改了我的代码,但它不起作用,我不知道为什么。

我的要求是

  

编写一个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:");
    }
}   
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确,按此顺序字面意思是按照给定的顺序。

如果是这种情况,你需要正则表达式。忘记计算字符。

  • 一个或多个大写字母[A-Z]+
  • 两个小写字母[a-z]{2}
  • 1位或2位\d{1,2}
  • 零或1个大写字母[A-Z]?
  • 这组中的任何两个人@#$%^&amp; [@#$%^&]{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