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.
As previously answered, you should chek all the password characters first. Count your digits and finally check if count is smaller than 2. Here is the referring code.
package Method;
/* 2. Write a Java method to check whether a string is a valid password. Password rules: A password must have at least ten characters. A password consists of only letters and digits. A password must contain at least two digits.
Expected Output:
Input a password (You are agreeing to the above Terms and Conditions.): abcd1234
Password is valid: abcd1234 */
public class CheckPassword {
}
Suppose a valid password has:
Code:
You almost got it. There are some errors though:
i < password.length() - 1
is wrong)