我有两个类: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设置器)。
当使用采用SystemManagement的构造函数创建新的String对象时,将忽略该参数,并且password为空,因为nextPassword()始终返回空的String

07-24 09:24