Home > OS >  If this then include that (java password generator) [closed]
If this then include that (java password generator) [closed]

Time:09-17

I am making a password generator and I want the user to have the option to choose if they want to include upper/lower case letters, special chars and numbers but I am not sure how to do this with the code that I have right now without making too many if statements.

private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMERIC = "0123456789";
private static final String SPECIAL_CHARS = "!@#$%^&*_= -/";
private static SecureRandom random = new SecureRandom(); 

Above are the different chars that can be used to generate the password.

public void generatePasswordAgain(ActionEvent event) throws IOException {
    genPassword.setText(generatePassword(length, ALPHA_CAPS   ALPHA   SPECIAL_CHARS   NUMERIC));
}

Above is the function called when you want to generate a password. And below is the code that actually generates the password.

public static String generatePassword(int len, String dic) {
    String result = "";
    for (int i = 0; i < len; i  ) {
        int index = random.nextInt(dic.length());
        result  = dic.charAt(index);
    }
    return result;
}

I want to give the person using the program a chance to choose what type of chars they want to include in their program. Is there a way to do this without making too many if statements?

The persons demands for the chars they want to include are defined by booleans.

CodePudding user response:

If you want to avoid switch case and if else cascades, you may use a single line trinary operator.

private static final String EMPTY = "";

... // StringUtils.EMPTY can also be used.

boolean alphaUpper, alphaLower, numeric, special;

... // set your boolean flags here

genPassword.setText(generatePassword(length, (alphaUpper ? ALPHA_CAPS : EMPTY)   (alphaLower ? ALPHA : EMPTY)   (special ? SPECIAL_CHARS : EMPTY)   (numeric ? NUMERIC : EMPTY)));
  • Related