Answer to Question #162353 in Java | JSP | JSF for asd

Question #162353

Write a Java method to check whether a string is a valid password. Each character must be stored in a character array


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:


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


Password is valid: abcd1234



1
Expert's answer
2021-02-09T15:28:50-0500
import java.util.Scanner;

public class Main {

    public static boolean isValid(char[] password) {
        if (password.length < 10) {
            return false;
        }
        int digit = 0;
        for (int i = 0; i < password.length; i++) {
            if (password[i] > '0' && password[i] < '9') {
                digit++;
            }
            if (!((password[i] > 'a' && password[i] < 'z') ||
                    (password[i] > 'A' && password[i] < 'Z') ||
                    (password[i] > '0' && password[i] < '9'))) {
                return false;
            }
        }
        return digit >= 2;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Input a password (You are agreeing to the above Terms and Conditions.): ");
        String password = in.nextLine();
        System.out.println("Password is " + (isValid(password.toCharArray()) ? "valid: " : "invalid: ") + password);
    }
}

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