Suppose a website impose the following rules for passwords. 1. A password must h
ID: 3930071 • Letter: S
Question
Suppose a website impose the following rules for passwords.
1. A password must have at least eight characters.
2. A password consists of only letters and digits.
3. A password must contain at least two digits.
Write a program that prompts the user to enter a password. If the user enters a invalid password, the program needs to tell the user why it is invalid and ask the user to enter another password. The program should stop only when the user enters a valid password.
Here is one sample run to check these 4 passwords in order
Enter a new password: My password18
Invalid: Only letters and digits
My question what do i write to make the program state that it is invalid and say Only letters and digits. When i enter the password My password18, theres a space in there.
Ive written the program so far and it works, its just missing that part. Its in Java Language
Explanation / Answer
When you are enter the space in your password the program is missing it because you are not validating only letter and digit. We have to just write a logic to accept only letters and digits no other special character. I am writing the logic function for the problem.
public static boolean isValid(String password) {
if (password.length() < 8) {
return false;
} else {
char c;
int count = 1;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
if (count < 2) {
return false;
}
}
}
}
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.