Search code examples
javapasswordsbluej

Checking Password Code


Problem Description:

Some Websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rule is 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 rule is followed or "invalid password" otherwise.

This is what I have so far:

import java.util.*;  
import java.lang.String;  
import java.lang.Character;  

/**
 * @author CD
 * 12/2/2012
 * This class will check your password to make sure it fits the minimum set     requirements.
 */
public class CheckingPassword {  

    public static void main(String[] args) {  
        Scanner input = new Scanner(System.in);  
        System.out.print("Please enter a Password: ");  
        String password = input.next();  
        if (isValid(password)) {  
            System.out.println("Valid Password");  
        } else {  
            System.out.println("Invalid Password");  
        }  
    }  

    public static boolean isValid(String password) {  
        //return true if and only if password:
        //1. have at least eight characters.
        //2. consists of only letters and digits.
        //3. must contain at least two digits.
        if (password.length() < 8) {   
            return false;  
        } else {      
            char c;  
            int count = 1;   
            for (int i = 0; i < password.length() - 1; i++) {  
                c = password.charAt(i);  
                if (!Character.isLetterOrDigit(c)) {          
                    return false;  
                } else if (Character.isDigit(c)) {  
                    count++;  
                    if (count < 2)   {     
                        return false;  
                    }     
                }  
            }  
        }  
        return true;  
    }  
}

When I run the program it only checks for the length of the password, I cannot figure out how to make sure it is checking for both letters and digits, and to have at least two digits in the password.


Solution

  • You almost got it. There are some errors though:

    • you're not iterating over all the chars of the password (i < password.length() - 1 is wrong)
    • you start with a digit count of 1 instead of 0
    • you make the check that the count of digits is at least 2 as soon as you meet the first digit, instead of checking it after you have scanned all the characters