如何描述Java的PasswordValidator规则

时间:2018-11-10 19:46:29

标签: java

任何人都可以教我如何在用户类型-1退出程序和密码错误时重新输入密码,但是对于此代码,我遇到了很大的问题,我不知道为什么用户输入错误密码但java仍然显示密码有效但是当我使用else时,那只会显示我的规则的一件事 谢谢

package test;

import java.util.Scanner;

class PasswordValidator {

public static void main(String[] args) {
    while(true) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter user name : ");
    String username = sc.nextLine();
    System.out.print("Enter password : ");


    String password;
    boolean hasLength;
    boolean hasUppercase;
    boolean hasLowercase;
    boolean hasDigit;
    boolean hasSpecial;
    boolean whitespace;
    boolean userpass;


    password = sc.nextLine();
    hasLength = password.length() > 10;
    hasLength = password.length() < 7;
    hasUppercase = !password.equals(password.toUpperCase());
    hasLowercase = !password.equals(password.toLowerCase());
    hasDigit = password.matches(".*[0-9].*");// checks for digits
    hasSpecial = !password.matches("[A-Za-z0-9]*"); // for anything not a letter in the ABC's
    whitespace = !password.matches(".*\\s.*");
    userpass = !password.matches(username);


    if (hasLength) {
        System.out.println("Password should be within 7 to 10 characters in length");
    }
     if (!hasUppercase) {
        System.out.println("Password should be at least one upper-case alphabet");
    }
     if (!hasLowercase) {
        System.out.println("Password should be at least one lower-case alphabet");
    }
     if (!hasDigit) {
        System.out.println("Password should cantain at least one number");
    }
     if (!hasSpecial) {
        System.out.println("Password should be at least one special character");
    }
     if (!whitespace) {
        System.out.println("Password should not contain whitespace.");
    }
     if (!userpass) {           
        System.out.println("Password should not contain or be the same as user name.");
    }       
    else {
        System.out.println("Password is valid.");       
    }   







}}}

1 个答案:

答案 0 :(得分:0)

像结尾处一样的正则表达式可以进一步压缩。

这是一个好链接:

Regexp Java for password validation