0

I am new to java and I am wondering how I would add options to my password generator such as 'How many digits do you want??' or 'How many symbols do you want?' in the generated password.

This is the code I have so far and I would like some help on how I would do this.

Thanks in advance.

public static void main(String[] args) {

    String result = generatePassword(10);
    System.out.println(result);
}

public static String generatePassword(int length) {
    String password = "";

    for (int i = 0; i < length - 2; i++) {
        password = password + randomCharacter("abcdefghijklmnopqrstuvwxyz");
    }

    String randomDigit = randomCharacter("0123456789");
    password = insertAtRandom(password, randomDigit);

    String randomSymbol = randomCharacter("!#$%&'()*+,-.:<=>?@[}^_{}~"); 
    password = insertAtRandom(password, randomSymbol);

    String randomCapital = randomCharacter ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    password = insertAtRandom(password, randomCapital);

    System.out.println("This is your new password:");
    return password;
}

public static String randomCharacter(String characters) {
    int n = characters.length();
    int r = (int) (n * Math.random());
    return characters.substring(r, r + 1);
}

public static String insertAtRandom(String str, String toInsert) {
    int n = str.length(); 
    int r = (int)((n + 1) * Math.random());
    return str.substring(0, r ) + toInsert + str.substring(r);
}

}

  • you solution seems ok, i didn't understand your question, are you asking how to get input from the user? – shahaf Apr 22 '18 at 16:27
  • Please see https://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java – Vietvo Apr 22 '18 at 16:28

1 Answers1

0

One way you could do it is pass in multiple parameters?

i.e generatePassword(int length, int noDigits, int noSymbols)

Then replace the randomDigit

for (int i = 0; i < noDigits - 2; i++) { password = password + randomCharacter("0123456789"); }

Or

for (int i = 0; i < noSymbols - 2; i++) { password = password + randomCharacter("!#$%&'()*+,-.:<=>?@[}^_{}~"); }

If you want a user input you could try a JOptionPane such as:

int digits = Integer.parseInt(JOptionPane.showInputDialog("How many digits?"));

Apart from this I think your solution seems fine as it is. Keep up the practising!

teamyates
  • 414
  • 1
  • 7
  • 25