Coding Solution 03

Write a Java program to check if a given String is a Valid Password or Not.





Code:
import java.util.Scanner;

public class Exercise11 {
    
public static final int PASSWORD_LENGTH = 8;

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print(
                "1. A password must have at least eight characters.\n" +
                "2. A password consists of only letters and digits.\n" +
                "3. A password must contain at least two digits \n" +
                "Input a password (You are agreeing to the above Terms and Conditions.): ");
        String s = input.nextLine();

        if (is_Valid_Password(s)) {
            System.out.println("\nPassword is valid: " + s);
        } else {
            System.out.println("\nNot a valid password: " + s);
        }

    }

    public static boolean is_Valid_Password(String password) {

        if (password.length() < PASSWORD_LENGTH) return false;

        int charCount = 0;
        int numCount = 0;
        for (int i = 0; i < password.length(); i++) {

            char ch = password.charAt(i);

            if (is_Numeric(ch)) numCount++;
            else if (is_Letter(ch)) charCount++;
            else return false;
        }


        return (charCount >= 2 && numCount >= 2);
    }

    public static boolean is_Letter(char ch) {
        ch = Character.toUpperCase(ch);
        return (ch >= 'A' && ch <= 'Z');
    }


    public static boolean is_Numeric(char ch) {

        return (ch >= '0' && ch <= '9');
    }

}




Output:

Write a Java program to check if a given String is a Valid Password or Not
Output 1

Write a Java program to check if a given String is a Valid Password or Not
Output 2



Link: https://ide.geeksforgeeks.org/t83WyghRCD




I hereby confirm that the coding solution is written by me and complied & run at GreeksForGreeks Online Complier.


#MAR #MARACTIVITY #MARPOINTS #MAKAUT #SKFGI #CODINGSOLUTION
#mar #maractivity #marpoints #makaut #skfgi #codingsolution

Comments