In: Computer Science
2. Write a Java program to read a string (a password)from the user and then
check that the password conforms to the corporate password policy.
The policy is:
1) the password must be at least 8 characters
2) the password must contain at least two upper case letters
3) the password must contain at least one digit
4) the password cannot begin with a digit
Use a for loop to step through the string.
Output “Password OK” if the password conforms, otherwise
output “Password does not conform to the policy.”
*****IN JAVA**********
Hi, Please find java code for given problem statement below:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int passwordLength = 0, upperCaseCharacterCount = 0;
boolean isDigitPresent = false,isBeginWithDigit = false;
//Accepting password from user
Scanner sc = new Scanner(System.in);
System.out.print("Enter password : ");
String password = sc.nextLine();
//Checking password given conditions.
for (int i =0 ; i<password.length(); i++){
++passwordLength;
char ch = password.charAt(i);
if (i == 0 && Character.isDigit(ch)){
isBeginWithDigit = true;
break;
}
if (Character.isUpperCase(ch))
++upperCaseCharacterCount;
if (Character.isDigit(ch))
isDigitPresent = true;
}
//If all password conditions are true then print password OK
if (passwordLength >= 8 && isDigitPresent && upperCaseCharacterCount >=2 && !isBeginWithDigit)
System.out.print("Password OK");
else
System.out.println("Password does not conform to the policy");
}
}
Also find screenshot of above code and its output for better understanding and indentation. Also have a look on comments as well
Output
Explanation: