views:

127

answers:

5

In my Generator class ,I make a new password and also I have a SystemManagements class which imports Generator class (it is in the other package) and I have some information like name and family of user and I make an object which its type is SystemManagement but when i call getPassword() on my object it will return 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; }

A: 

password1.length() is 0 first time, so it never gets filled?

Ariel
That would return an empty string, not null.
erickson
A: 
 StringBuffer password1 = new StringBuffer();
    for (int i = 0; i < password1.length(); i++) {

I would imagine that that would be 0 for the length of the string buffer.

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

The for loop will never run as password1.length() will be 0 at this time.

willcodejavaforfood
+1  A: 

I can spot a couple of problems with your code:

  • Your nextPassword() method always returns an Empty String as the password because you iterate over an empty StringBuilder with length 0.

  • When your create a new SystemManagement object with the parameter-less constructor, your password is null because you never assign nothing to it (unless you use the setPassword setter).

  • When your create a new SystemManagement object with the constructor that takes a String, you ignore the parameter and your password is empty because nextPassword() always returns an Empty String.

bruno conde