38.5k views
5 votes
Having a secure password is a very important practice, when much of our information is stored online. Write a program that validates a new password, following these rules:

• The password must be at least 8 characters long.
• The password must have at least one uppercase and one lowercase letter
• The password must have at least one digit.

Write a program that asks for a password, then asks again to confirm it. If the passwords don’t match or the rules are not fulfilled, prompt again. Your program should include a method that checks whether a password is valid.

User Joe Caruso
by
6.3k points

1 Answer

4 votes

public static boolean isValid(String password) {

Boolean atleastOneUpper = false;

Boolean atleastOneLower = false;

Boolean atleastOneDigit = false;

// If its less then 8 characters, its automatically not valid

if (password.length() < 8) {

return false;

}

for (int i = 0; i < password.length(); i++) {

// Lets iterate over only once.

if (Character.isUpperCase(password.charAt(i))) {

atleastOneUpper = true;

}

else if (Character.isLowerCase(password.charAt(i))) {

atleastOneLower = true;

}

else if (Character.isDigit(password.charAt(i))) {

atleastOneDigit = true;

}

}

return (atleastOneUpper && atleastOneLower && atleastOneDigit);

// Return true if the password is atleast eight characters long, has atleast one upper, lower and digit

}

User Gmaniac
by
6.4k points