2016-10-15 6 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を使用してください:)