2016-10-15 3 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을 사용하십시오 :)