samedi 23 avril 2016

Not Generating Random Characters on Each Call

I'm hoping someone can point me in the direction of figuring out why my code does not create a random string of alphabetic characters each time it is called in the main class.

Here is my password randomizer class:

import java.util.Random;

public class PasswordRandomizer {
    private Random random = new Random();
    private int length;
    private int num;
    private String password = "";
    private String alphabet = "abcdefghijklmnopqrstuvwxyz";
    private char character;

    public PasswordRandomizer(int length) {
        // Initialize the variable
        this.length = length;
    }

    public String createPassword() {
        while ( length > 0 ) {           
            num = this.random.nextInt(26);
            character = alphabet.charAt(num);
            password += character;
            length--;
        }
        return password;
    }
}

And for each call it only produces the exact same password. For example:

    public class Program {
    public static void main(String[] args) {
        PasswordRandomizer password = new PasswordRandomizer(13);
        System.out.println("Password: " + password.createPassword());
        System.out.println("Password: " + password.createPassword());
        System.out.println("Password: " + password.createPassword());
        System.out.println("Password: " + password.createPassword());
    }
}




Aucun commentaire:

Enregistrer un commentaire