如何制作密码程序

时间:2022-06-26 22:49:35

I am trying to create a program that asks the user to enter a password with a condition of at least 10 letter characters with at least 2 numbers. So far this is what I've come up with, but the program reads any amount of letters or numbers as a valid password.

我正在尝试创建一个程序,要求用户输入一个条件至少包含10个字母且至少包含2个数字的密码。到目前为止,这是我提出的,但程序会将任意数量的字母或数字作为有效密码。

package password;
import java.util.Scanner;

public class Password {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       String password;
       Scanner keyboard = new Scanner(System.in);
       System.out.println("Enter a password with 10 characters total with "+
                "2 numbers: ");
        password=keyboard.nextLine();



        System.exit(0);


    }

    public static boolean passwordCheck(String password)

   {
       if (password.length() <10) return false ;

               int letterCount = 0;
               int numCount =0;
               for (int i =0; i < password.length (); i++ )
               {char ch = password.charAt(i);

               if (letter(ch)) letterCount++; 
               else if (numeric(ch)) numCount++;
               else return false; 

               }   

    return (letterCount >= 2 && numCount >= 2);
            } 
    public static boolean letter(char ch)
    {
         return (ch >= 'a' && ch <= 'z') ||
           (ch >= 'A' && ch <= 'Z') ;
    }


    public static boolean numeric(char ch)
    {
        return(ch >= '0' && ch <= '9');
    }


}

1 个解决方案

#1


1  

Try this.

     if (password.length() < 10) {   
        return false;  
    } else {      
        char c;  
        int count = 1;   
        for (int i = 1; i < password.length(); i++) {  
            c = password.charAt(i);  
            if (!Character.isLetterOrDigit(c)) {          
                return false;  
            } else if (Character.isDigit(c)) {  
                count++;  
                if (count < 2)   {     
                    return false;  
                }     
            }  
        }  
    }  
    return true;  
    }

#1


1  

Try this.

     if (password.length() < 10) {   
        return false;  
    } else {      
        char c;  
        int count = 1;   
        for (int i = 1; i < password.length(); i++) {  
            c = password.charAt(i);  
            if (!Character.isLetterOrDigit(c)) {          
                return false;  
            } else if (Character.isDigit(c)) {  
                count++;  
                if (count < 2)   {     
                    return false;  
                }     
            }  
        }  
    }  
    return true;  
    }