Java - 检查在线密码

时间:2016-10-15 14:32:11

标签: java regex passwords

这是来自梁的Java书。基本上,我必须检查一个方法是否可以使用某个单词作为密码。

/*
(Check password) Some websites impose certain rules for passwords. Write a
method that checks whether a string is a valid password. Suppose the password
rules are as follows:
■ A password must have at least eight characters.
■ A password consists of only letters and digits.
■ A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays Valid
Password if the rules are followed or Invalid Password otherwise.
*/



    import java.util.Scanner;

    public class Test {
        public static void main(String[] args) {

            System.out.println("This program checks if the password prompted is valid, enter a password:");
            Scanner input = new Scanner(System.in);
            String password = input.nextLine();

            if (isValidPassword(password))
                System.out.println("The password is valid.");
            else
                System.out.println("The password is not valid.");


        public static boolean isValidPassword (String password) {
            if (password.length() >= 8)  {
                // if (regex to include only alphanumeric characters?
                // if "password" contains at least two digits...


            return true;

    }

另外,如果(不是必需的话)我会显示确切的错误类型?例如,如果我通知用户只发生了一种错误(例如"您的密码长度没问题,但密码中没有数字")

1 个答案:

答案 0 :(得分:0)

我会这样做:

    public class Test {

    public static String passwordChecker(String s){
        String response = "The password";
        int countdigits = 0;
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher(s);
        while(matcher.find()){
            ++countdigits;
        }
        if(s.length() >= 8){
        response = response + ": \n-is too short (min. 8)";
        }
        else if(!(s.toLowerCase().matches("[a-z]+") && s.matches("[0-9]+"))){
            response = response + "\n-is not alphanumeric";
        }
        else if(countdigits < 2){
            response = response + "\n-it doesn't contains at least 2 digits";
        }
        else{
            response = response + " ok";
        }
        return response;
        }


    public static void main(String[] args) {
        System.out.println("This program checks if the password prompted is valid, enter a password:");
        Scanner input = new Scanner(System.in);
        String password = input.nextLine();
        System.out.println(passwordChecker(password));
    }

}
哎呀,我忘了添加规则;好吧,只需使用System.out.println :)