In: Computer Science
// Java program to input two passwords and check if both the
passwords match
import java.util.Scanner;
public class PasswordChecker {
  
   // method to return if password is valid or not i.e it
follows all the 4 rules
   private static boolean validPassword(String
password)
   {
       boolean lengthValid = false,
upperValid = false, lowerValid = false, digitValid = false;
       // check if length of password is
atleast 8 characters long
       if(password.length() >= 8)
           lengthValid =
true;
      
       // loop to check if password
contains atleast one lowercase, uppercase and digit
       for(int
i=0;i<password.length();i++)
       {
          
           // check if ith
character is uppercase
          
if(Character.isUpperCase(password.charAt(i)))
          
    upperValid = true;
           // check if ith
character is lowercase  
           else
if(Character.isLowerCase(password.charAt(i)))
          
    lowerValid = true;
           // check if ith
character is digit
           else
if(Character.isDigit(password.charAt(i)))
          
    digitValid = true;
       }
      
       // return if the password is
valid
       return(lengthValid &&
upperValid && lowerValid && digitValid);
   }
  
   // method to return if the both passwords match
   private static boolean samePassword(String password,
String confirmPassword)
   {
      
return(password.equals(confirmPassword));
   }
public static void main(String[] args) {
       Scanner scan = new
Scanner(System.in);
       String password,
confirmPassword;
       boolean correctPassword =
false;
       // input the password
       System.out.print("Enter password :
");
       password = scan.nextLine();
      
       // loop to validate password and
re-prompt until valid
      
while(!validPassword(password))
       {
          
System.out.println("Invalid password");
          
System.out.print("Enter password : ");
           password =
scan.nextLine();
       }
      
       // loop to input the passwords
again and allow the user 3 tries
       for(int i=0;i<3;i++)
       {
          
System.out.print("Enter the password again : ");
           confirmPassword
= scan.nextLine();
           // check if
password is same
          
if(samePassword(password,confirmPassword))
           {
          
    correctPassword = true;
          
    break;
           }
       }
       // check if passwords match
after 3 tries and display the message accordingly
       if(!correctPassword)
          
System.out.println("Both passwords doesn't match");
       else
          
System.out.println("Both passwords match");
      
       scan.close();
   }
}
//end of program
Output:
