为什么我的方法返回空密码?

时间:2009-11-20 14:52:34

标签: java null passwords

我有两个类: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;
    }
}

SystemManagement:

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;
    }
}

5 个答案:

答案 0 :(得分:3)

我可以发现您的代码存在一些问题:

  • 您的nextPassword()方法始终返回一个空String作为密码,因为您遍历一个长度为0的空StringBuilder

  • 使用无参数构造函数创建新的SystemManagement对象时,password为空,因为您没有为其指定任何内容(除非您使用setPassword setter)

  • 使用带有SystemManagement的构造函数创建新的String对象时,忽略该参数,password为空,因为nextPassword()始终返回空String

答案 1 :(得分:0)

password1.length()第一次为0,所以它永远不会被填充?

答案 2 :(得分:0)

 StringBuffer password1 = new StringBuffer();
    for (int i = 0; i < password1.length(); i++) {

我认为对于字符串缓冲区的0,这将是length

答案 3 :(得分:0)

如果调用不带参数的构造函数(如sys = new SystemManagement();),则永远不会设置新对象的password成员。只有当您调用带有String的构造函数时才会发生这种情况 - 您忽略了它。

答案 4 :(得分:0)

StringBuffer password1 = new StringBuffer();
for (int i = 0; i < password1.length(); i++) {
    password1.append(allowedCharacters[random.nextInt(allowedCharacters.length)]);
}

for循环永远不会运行,因为此时password1.length()将为0。