Chapter 7 #4, p. 386; Programming Exercises; JAVA PROGRAMMING; 8th Edition; Joyc
ID: 3763624 • Letter: C
Question
Chapter 7 #4, p. 386; Programming Exercises; JAVA PROGRAMMING; 8th Edition; Joyce Farrell. THANK YOU!!!
#4. Write an application that prompts that 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 ValidatePassword.java
Output/example
Enter a string: 23testkk
The password did not have enough of the following:
uppercase letters
Enter a string: TESTabc12345
Valid password
SIR/MADAM, THANK YOU!!!
Explanation / Answer
import java.util.Scanner;
public class ValidatePassword {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
do {
System.out.print(" Enter Password:");
String password = "";
password = scanner.nextLine();
int upperFound = 0, lowerFound = 0, digitFound = 0;
for (char c : password.toCharArray()) {
if (Character.isUpperCase(c)) {
upperFound++;
} else if (Character.isLowerCase(c)) {
lowerFound++;
} else if (Character.isDigit(c)) {
digitFound++;
}
}
String errorMessage = "";
if (upperFound < 2) {
errorMessage += " uppercase letters";
}
if (lowerFound < 2) {
errorMessage += " lowercase letters";
}
if (digitFound < 2) {
errorMessage += " digits";
}
// System.out.println(errorMessage);
if (errorMessage.length() > 1) {
System.out
.println("The password did not have enough of the following: "
+ errorMessage);
} else {
System.out.println("Valid password");
break;
}
} while (true);
}
}
output:
Enter Password:23testkk
The password did not have enough of the following:
uppercase letters
Enter Password:TESTabc12345
Valid password