using while loop to check password Suppose a website impose
using while loop to check password
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.
make the program work for handling one password correctly. then add the WHILE LOOP to handle potentically multiple passwords so the program will stop only when a valid password is typed. Deliver: pw - password-pass 3211- pass3211
Solution
Password.java
import java.util.Scanner;
public class Password
{
public static boolean isValid(String password)
{
int digitCount = 0;
boolean hasSymbol = false;
if(password.length() >= 8) {//Checks for length.
int i = 0;
while( i < password.length()) //For each character.
{
char c = password.charAt(i);
if(Character.isDigit(c)) //If digit, increment counter.
digitCount++;
if(!((c >=\'a\' && c <=\'z\') || (c >=\'A\' && c <= \'Z\') ||(c>=\'0\' && c<=\'9\') )) //If has symbol, mark flag.
hasSymbol = true;
i++;
}
} else {
System.out.println(\"Password length should be no less than 8.\");
return false;
}
if(digitCount < 2) {
System.out.println(\"Password should contain minimum 2 digits.\");
return false;
}
if(hasSymbol) {
System.out.println(\"Password should contain atleast one special characters from !, @, #, $, %, ^, &, *, (, ), ?\");
return false;
}
return true;
}
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print(\"Ennter the password: \");
String pass = scan.nextLine();
while(!isValid(pass)){
System.out.print(\"Ennter the password: \");
pass = scan.nextLine();
}
}
}
Output:
Ennter the password: pass
Password length should be no less than 8.
Ennter the password: password
Password should contain minimum 2 digits.
Ennter the password: pass 3211
Password should contain atleast one special characters from !, @, #, $, %, ^, &, *, (, ), ?
Ennter the password: pass3211

