我是java的新手,我想知道如何为我的密码生成器添加选项,例如“你想要多少位数?”或者“你想要多少个符号?”在生成的密码中。
这是我到目前为止的代码,我希望能帮到我如何做到这一点。
提前致谢。
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);
}
}
答案 0 :(得分:0)
你能做到的一种方法是传递多个参数?
即
generatePassword(int length, int noDigits, int noSymbols)
然后替换randomDigit
for (int i = 0; i < noDigits - 2; i++) {
password = password + randomCharacter("0123456789");
}
或者
for (int i = 0; i < noSymbols - 2; i++) {
password = password + randomCharacter("!#$%&'()*+,-.:<=>?@[}^_{}~");
}
如果您想要用户输入,可以尝试使用JOptionPane,例如:
int digits = Integer.parseInt(JOptionPane.showInputDialog("How many digits?"));
除此之外,我认为你的解决方案看起来很好。继续练习!