我认为除了一件事我一切都有效。当我在main上多次调用该方法时,它会不断创建相同的密码。
以下是密码创建的类:
import java.util.Random;
public class PasswordRandomizer {
// Define the variables
private int length;
private String password;
private Random random = new Random();
private char symbol;
public PasswordRandomizer(int length) {
// Initialize the variable
password = "";
this.length = length;
while (this.password.length() < this.length) {
this.symbol = "abcdefghijklmnopqrstuvwxyz".charAt(this.random.nextInt(25));
this.password += symbol;
}
}
public String createPassword() {
// write code that returns a randomized password
return this.password;
}
}
这就是我的主要内容:
public class Program {
public static void main(String[] args) {
PasswordRandomizer randomizer = new PasswordRandomizer(13);
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
System.out.println("Password: " + randomizer.createPassword());
}
}
我会得到这样的输出:
Password: seggdpsptkxqo
Password: seggdpsptkxqo
Password: seggdpsptkxqo
Password: seggdpsptkxqo
随意指出我遇到的任何其他错误或坏习惯,我对此仍然很陌生。
答案 0 :(得分:4)
让我们来看看你的代码。
在构造函数中,初始化长度,然后生成密码:
public PasswordRandomizer(int length) {
// Initialize the variable
password = "";
this.length = length;
while (this.password.length() < this.length) {
this.symbol = "abcdefghijklmnopqrstuvwxyz".charAt(this.random.nextInt(25));
this.password += symbol;
}
}
然后,在您的createPassword
方法中,只返回在构造函数中生成的密码,而不更改它:
public String createPassword() {
// write code that returns a randomized password
return this.password;
}
所以,每当你打电话给createPassword
时,你都会得到同样的东西。让我们看看如果我们将生成密码的代码移到createPassword
方法中会发生什么:
import java.util.Random;
public class PasswordRandomizer {
// Define the variables
private int length;
private String password;
private Random random = new Random();
private char symbol;
public PasswordRandomizer(int length) {
// Initialize the variable
this.length = length;
}
public String createPassword() {
// write code that returns a randomized password
password = "";
while (this.password.length() < this.length) {
this.symbol = "abcdefghijklmnopqrstuvwxyz".charAt(this.random.nextInt(26));
this.password += symbol;
}
return this.password;
}
}
现在,当我们运行您的Program
时,您会得到如下输出:
Password: mvlqqgfmotldc
Password: inneuyuynqakd
Password: hstlfsfspfaua
Password: jgngsmdiguxcy
答案 1 :(得分:2)
您应该创建一个新的PasswordRandomizer程序,否则,每次都不会创建密码。例如,如果您不重写PasswordRandomizer类,则可以执行以下操作:
package test;
public class Program {
public static void main(String[] args) {
System.out.println("Password: " + new PasswordRandomizer(13).createPassword());
System.out.println("Password: " + new PasswordRandomizer(13).createPassword());
System.out.println("Password: " + new PasswordRandomizer(13).createPassword());
System.out.println("Password: " + new PasswordRandomizer(13).createPassword());
}
}
答案 2 :(得分:0)
您可以使用Apache Commons Lang库。
在RandomStringUtils中有一种生成具有一定长度的随机字符串的方法:randomAlphabetic(int count)