In: Computer Science
I need a basic and simple Java code for this exercise:
(Check password) Some websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rules are as follows:
■ A password must have at least eight characters. A character is alpha or digit.
■ A password consists of only letters and digits. No other symbols.
■ A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays Valid Password if the rules are followed or Invalid Password otherwise. For example, “abcdef12” is legal, “12345678” is legal, “$abcde12” is not legal, “abcdefgh” is not legal.
CheckingPassword.java
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class CheckingPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
//return true if and only if password:
//1. have at least eight characters.
//2. consists of only letters and digits.
//3. must contain at least two digits.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 0;
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;
}
}
OUTPUT: