Search code examples
javastringpasswordsuppercaselowercase

How to check if there are 2 upper case letters, 3 lower case letters, and 1 number in JAVA


Please help i have been stuck for a good part of an afternoon already and cant really find/understand answers from other resources. I need to receive a password input from the user and need to test whether or not the password contains:

  • Two Upper case letters
  • Three Lower case letters
  • One number

here is my code:

import javax.swing.JOptionPane;
public class PracticePassword {

    public static void main(String[] args) {
        String originalPw;
        // TODO Auto-generated method stub
        String newPw;
        int pwLength;
        int i;
        char c;

        newPw = JOptionPane.showInputDialog(null, "Please enter a password" + 
        " that contains the following:" + "\n"
        + "**TWO upper case letters" + "\n" + "**THREE lower case letters" + "\n"
        + "**ONE number");
        originalPw = newPw;
        pwLength = newPw.length();

        for (i = 0; i <= pwLength; i++) {
            boolean hasUpperCase = !originalPw.equals(originalPw.toUpperCase());
            boolean hasLowerCase = !originalPw.equals(originalPw.toUpperCase());

            if(!hasUpperCase){
                System.out.println("You have three upper case letters, good job.");
            }
            else {
                System.out.println("You must have three upper case letters");
            }
        }

    }   
}

If it looks like i have no clue what i am doing towards the end its because i dont. Please help. thank you:)

thanks for your replies everyone. i shouldve been more specific. I guess what i shoudlve asked if there are any methods out there or structures i can implement in my code to make sure the user input meets those specifications. I see now that my code is very incomplete. i am going over notes now to improve my code.


Solution

  • This looks like a homework question so I won't solve it directly. However here are some steps you could take:

    • Create a method to validate the input (public static boolean isValid(String str))

    • Convert the String to a character Array. (There's a method for that!)

    • Iterate over the letters and keep track of how many upper and lower case letters there are and how many digits there are. (Using Character.isDigit(), Character.isUpperCase() and Character.isLowerCase())

    • If all the requirements are met, return true. Return false otherwise.