Write an application that accepts a users password from the
Write an application that accepts a user\'s password from the keyboard. When the entered password is less than six characters, more than ten characters, or does not contain at least one letter and one digit, prompt the user again.
When the user\'s entry meets all the password requirements, prompt the user to re-enter the password, and do not let the user continue until the second password matches the first one.
Save the application as Password.java
Solution
Password.java
import java.util.Scanner;
public class Password
{
public static boolean isValid(String password)
{
int digitCount = 0;
int isLetter = 0;
if(password.length() >= 6 && password.length() <= 10) {//Checks for length.
int i = 0;
while( i < password.length()) //For each character.
{
char c = password.charAt(i);
if(Character.isDigit(c)) //If digit, increment counter.
digitCount++;
if(((c >=\'a\' && c <=\'z\') || (c >=\'A\' && c <= \'Z\') )) //If letter, increment counter
isLetter++;
i++;
}
} else {
System.out.println(\"Password length should be greater than six characters, less than ten characters.\");
return false;
}
if(digitCount < 1) {
System.out.println(\"Password should contain minimum 1 digits.\");
return false;
}
if(isLetter < 1) {
System.out.println(\"Password should contain minimum 1 letter.\");
return false;
}
return true;
}
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print(\"Ennter the password: \");
String pass = scan.nextLine();
while(!isValid(pass)){
System.out.print(\"Enter the password: \");
pass = scan.nextLine();
}
String reEmterPass = \"\";
while(!reEmterPass.equals(pass)){
System.out.print(\"Re-enter the password: \");
reEmterPass = scan.nextLine();
}
}
}
Output:
Ennter the password: 1234567
Password should contain minimum 1 letter.
Enter the password: pass
Password length should be greater than six characters, less than ten characters.
Enter the password: password
Password should contain minimum 1 digits.
Enter the password: password1
Re-enter the password: pass
Re-enter the password: password
Re-enter the password: password1

