Answer to Question #310740 in Java | JSP | JSF for shahriar

Question #310740

Write a Java method to check whether a string is a valid password.

Password rules:

A password must have at least ten characters.

A password consists of only letters and digits.

A password must contain at least two digits.

Expected Output:

1. A password must have at least ten characters.

2. A password consists of only letters and digits.

3. A password must contain at least two digits

Input a password (You are agreeing to the above Terms and Conditions.): abcd1234

Password is valid: abcd1234


1
Expert's answer
2022-03-13T15:11:17-0400
import java.util.Scanner;


public class App {


	/** Main Method */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in); // Create a Scanner
		System.out.print("Input a password (You are agreeing to the above Terms and Conditions.): ");
		String password = keyBoard.nextLine();


		if (isValidPassword(password)) {
			System.out.println("Password is valid: " + password);
		} else {
			System.out.println("Password is invalid: " + password);
		}
		keyBoard.close();
	}


	public static boolean isValidPassword(String password) {
		final int LENGTH_OF_VALID_PASSWORD = 10; // Valid length of password
		final int MINIMUM_NUMBER_OF_DIGITS = 2; // Minimum digits it must contain


		boolean validPassword = isLengthValid(password, LENGTH_OF_VALID_PASSWORD) && isOnlyLettersAndDigits(password)
				&& hasNDigits(password, MINIMUM_NUMBER_OF_DIGITS);


		return validPassword;
	}


	public static boolean isLengthValid(String password, int validLength) {
		return password.length() >= validLength;
	}


	public static boolean isOnlyLettersAndDigits(String password) {
		for (int i = 0; i < password.length(); i++) {
			if (!Character.isLetterOrDigit(password.charAt(i))) {
				return false;
			}
		}
		return true;
	}


	public static boolean hasNDigits(String password, int n) {
		int numberOfDigits = 0;
		for (int i = 0; i < password.length(); i++) {
			if (Character.isDigit(password.charAt(i))) {
				numberOfDigits++;
			}
			if (numberOfDigits >= n) {
				return true;
			}
		}
		return false;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS