所以我想做的是创建一个随机密码生成器,我设法使系统根据用户输入的字符长度生成一个随机的字符串。然后,我要做的就是询问用户是否要保存文件。在文件中,我要包含网站/应用程序的名称和密码。
我的问题是我无法获得将密码存储为变量的随机字符串,有人知道如何解决此问题吗?
代码如下所示:
System.out.println("Please enter the length of password that you require: ");
int passwordLength = sc.nextInt();
sc.nextLine();
Random r = new Random();
String alphabet = "abcde5678fghijklmn123opqrs?!£$%tuvwxyzABCDEFGHIJKLMN490@#/*(OPQRSTUVWXYZ)";
for (int i = 0; i < passwordLength; i++) {
System.out.print(alphabet.charAt(r.nextInt(alphabet.length())));
}
我相信您的意思是您希望将密码收集到String变量中,而不是打印每个字符。在一个完全可行的示例中,这是这样做的方法:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the length of password that you require: ");
int passwordLength = sc.nextInt();
sc.nextLine();
Random r = new Random();
String alphabet = "abcde5678fghijklmn123opqrs?!£$%tuvwxyzABCDEFGHIJKLMN490@#/*(OPQRSTUVWXYZ)";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < passwordLength; i++)
sb.append(alphabet.charAt(r.nextInt(alphabet.length())));
String password = sb.toString();
System.out.print(password);
}
结果:
Please enter the length of password that you require:
12
j$miDCadnJMd
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句