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);
}
}
Aucun commentaire:
Enregistrer un commentaire