2016-10-15 31 views
-1

這是來自Liang的Java Book。基本上,我必須檢查一個方法,如果某個單詞可以用作密碼。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; 

    } 

另外,如果有什麼(不需要),我會以顯示確切類型的錯誤?例如,如果我通知用戶只發生了一種錯誤(例如「您的密碼長度正常,但密碼中沒有數字」)?

+0

爲什麼downvote? – q1612749

回答

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 :)