![](/img/trans.png)
[英]Why Does My JSoup getTitle() method return null and not the webpage title?
[英]Why does my method return a null password?
我有两个类:Generator类和SystemManagement类。 在Generator类中,我可以生成一个密码。 SystemManagement类(从另一个程序包)导入Generator,并包含其他信息。
当我创建一个SystemManagement对象并对其调用getPassword()
时,我返回null
。 为什么会这样呢?
发电机:
public class Generator {
private static String password;
private static Generator instance;
public String nextPassword() {
char[] allowedCharacters = {'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5','6'};
SecureRandom random = new SecureRandom();
StringBuffer password1 = new StringBuffer();
for (int i = 0; i < password1.length(); i++) {
password1.append(allowedCharacters[random.nextInt(allowedCharacters.length)]);
}
password = password1.toString();
return password;
}
public String currentPassword() {
return password;
}
public static void setPassword(String password) {
Generator.password = password;
}
public static Generator getInstance() {
if (instance == null) {
instance = new Generator();
}
return instance;
}
}
系统管理:
public class SystemManagement implements Serializable {
private String name;
private String family;
private String password;
public SystemManagement() {
}
public SystemManagement(String password) {
this.password = Generator.getInstance().nextPassword();
}
public Students addStudent(String name, String family) {
Students student = new Students(name, family);
students.add(student);
return student;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
我可以发现您的代码有几个问题:
您的nextPassword()
方法始终返回一个空String
作为密码,因为您要遍历一个长度为0的空StringBuilder
。
使用无参数构造函数创建新的SystemManagement
对象时, password
为null,因为您没有为其分配任何内容(除非使用setPassword
setter)。
当使用带有String
的构造函数创建新的SystemManagement
对象时,将忽略该参数,并且password
为空,因为nextPassword()
始终返回空的String
。
password1.length()第一次是0,所以它永远不会被填充?
StringBuffer password1 = new StringBuffer();
for (int i = 0; i < password1.length(); i++) {
我想这对于字符串缓冲区的length
将为0
。
如果不带任何参数调用构造函数(例如sys = new SystemManagement();
),则永远不会设置新对象的password
成员。 仅当您调用带有String
的构造函数时,才会发生这种情况,而您会忽略它。
StringBuffer password1 = new StringBuffer();
for (int i = 0; i < password1.length(); i++) {
password1.append(allowedCharacters[random.nextInt(allowedCharacters.length)]);
}
for循环永远不会运行,因为password1.length()
将为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.