THIS QUESTION HAS TWO PARTS: A) Write an application that prompts the user for a
ID: 3864181 • Letter: T
Question
THIS QUESTION HAS TWO PARTS:
A) Write an application that prompts the user for a password that contains at least two uppercase letters, at least two lowercase letters, and at least two digits.
Continuously reprompt the user until a valid password is entered.
After each entry, display a message indicating whether the user was successful or the reason the user was not successful.
Save the file as Password.java.
B) Create the PasswordTest.java class that contains the main method and has an object to use the Password class
Explanation / Answer
Password.java:
import java.util.Scanner;
public class Password {
private boolean valid=false;
//valid will be set to true when a valid password is entered
public void readValidatePassword(){
Scanner scanner=new Scanner(System.in);
while(valid==false){
int digitCount=0, uppercaseCount=0, lowercaseCount=0;
System.out.println("Enter password: ");
String pass=scanner.nextLine();
for(int i=0;i<pass.length();i++){
if(Character.isDigit(pass.charAt(i))) digitCount++;
if(Character.isUpperCase(pass.charAt(i))) uppercaseCount++;
if(Character.isLowerCase(pass.charAt(i))) lowercaseCount++;
}
if(digitCount>=2 && uppercaseCount>=2 && lowercaseCount>=2){
System.out.println("You are successful. The password is valid.");
valid=true;
}
else if(digitCount<2){
System.out.println("You are not successful. There need to be at least 2 digits.");
}
else if(uppercaseCount<2){
System.out.println("You are not successful. There need to be at least 2 uppercase characters.");
}
else{
System.out.println("You are not successful. There need to be at least 2 lowercase characters.");
}
}
}
}
PasswordTest.java:
public class PasswordTest {
public static void main(String[] args) {
Password p1=new Password();
p1.readValidatePassword();
}
}
Sample Run:
Enter password:
jdKl
You are not successful. There need to be at least 2 digits.
Enter password:
KK12k
You are not successful. There need to be at least 2 lowercase characters.
Enter password:
Jjka113jd
You are not successful. There need to be at least 2 uppercase characters.
Enter password:
hgdKHJH*&)92
You are successful. The password is valid.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.